Getting started
This tutorial exposes key features of this library through mainly code
examples. For in-depth description of the modules, you’ll want to read
the API documentation.
If you have not installed couchdbkit yet, follow instruction on download page . Once you’ve done, you can write your first CouchDB document:
from couchdbkit.schema import Document from couchdbkit.schema.properties import * class Greeting(Document): author = StringProperty() content = StringProperty() date = DateTimeProperty()
Store the submitted Greetings
Here is the code to save a greet on database Greeting. We also see how to create a database.
import datetime from couchdbkit.client import Server from couchdbkit.session import create_session # server object server = Server() # create database try: server.create_db(“greetings”) except: pass # open a database session db = create_session(server, “greetings”) Greeting = db(Greeting) # create a new greet greet = Greeting( author=“Benoit”, content=“Welcome to simplecouchdb world”, date=datetime.datetime.utcnow() ) # save it db(greet).save()
Your document `greet` in `greetings` db. Each document is saved with a `doc_type` field that allow you to find easily each kind of document with the views. By default `doc_type` is the name of the class.
Now that you saved your document, you can update it :
greet.author = “Benoît Chesneau” greet.save()
Here we update the author name.
Note: You can notice that we don’t use the db object here to update. In fact db object was automatically associated with the Greeting class on first `save`. You could have done this asssociation before by doing :
Greeting = db(Greeting)
Dynamic properties
Mmm ok, but isn’t CouchDB storing documents schema less ? Do you want to add a property ? Easy:
greet.homepage = “http://www.e-engura.org” greet.save()
Now you just added an homepage property to the document.
Get all greetings
You first have to create a view and save it in the db. We call it `greeting/all`. To do this we will use the loader system of couchdbkit that allows you to send views to couchdb.
We create a folder that contains the design doc, and then the folder for the view. On unix :
mkdir -p ~/Work/couchdbkit/example/_design/greeting/views/all
In this folder we edit a file `map.js`:
function(doc) { if (doc.doc_type == “Greeting”) emit(doc._id, doc); }
On Textmate, you have :
A system will be provided to manage view creation and other things. As some noticed, this system works like couchapp.
Then we use `FileSystemDocsLoader` object to send the design document to CouchDB:
from couchdbkit.loaders import FileSystemDocsLoader loader = FileSystemDocsLoader(’/path/to/example/_design’) loader.sync(db, verbose=True)
The design doc is now in `greetings`database and you can get all greets :
greets = Greeting.view('greeting/all’)