chula.nosql.couch – Wrapper for python-couchdb

Module to extend http://code.google.com/p/couchdb-python/

Usefull links:

Document

class chula.nosql.couch.Document(id[, db_conn=None, document=None, server=None, shard=None, track_dirty=None])

CouchDB document abstraction class

__init__(id, **kwargs)
Parameters:
  • id (str) – Document id (this will be the CouchDB _id field)
  • document (dict) – Datastructure to clone
  • db (str) – Database to connect to
  • server (str) – Database server to use
  • shard (str) – Database shard to use
  • track_dirty (bool) – Only persist to the db when it’s actually changed
Return type:

chula.nosql.couch.Document (or subclass of)

Note

For server lookup logic, see chula.nosql.couch.connect()

Example use:

>>> from chula.nosql import couch
>>>
>>> # Create a couch model class that specifies it's db
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> # Create the new document with some stuff
>>> f = Foo('abc')
>>> f['color'] = 'red'
>>> f['options'] = [1, 2, 3]
>>> rev = f.persist()
>>>
>>> # The document has been persisted, so you can fetch it later
>>> f = Foo('abc')
>>> f['options'].pop()
3

Sharding:

>>> from chula.nosql import couch
>>>
>>> # Create a couch model class that specifies it's db
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> # Create the new document with some stuff
>>> f = Foo('Marry_Sue', shard='s')
>>> rev = f.persist()
>>>
>>> # The document has been persisted, so you can fetch it later
>>> f = Foo('Marry_Sue', shard='s')

What track_dirty does:

>>> import time
>>> from chula.nosql import couch
>>>
>>> # Create a couch model class that specifies it's db
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> doc_id = 'my-uniq-key-%s' % time.time()
>>>
>>> # Create the new document
>>> f = Foo(doc_id)
>>> rev1 = f.persist()
>>>
>>> # Fetch the document from scratch, revision is the same
>>> f = Foo(doc_id)
>>> rev1 == f['_rev']
True
>>>
>>> # Persisting the document unmodified doesn't actually talk to
>>> # the server, nothing has changed
>>> rev2 = f.persist()
>>> rev1 == rev2
True
>>>
>>> # Here we will get a new revision because the structure was mutated
>>> f['new_key'] = {'some-structure':[1, 2, 3, 4]}
>>> rev4 = f.persist()
>>> rev2 == rev4
False
classmethod delete(id, server=None, shard=None)

Delete the specified document from the specified databse (and shard if specified)

Parameters:
  • id (str) – Document id
  • server (str) – Database server to use
  • shard (str) – Database shard to use
Return type:

UTF-8 encoded str

>>> from chula.nosql import couch
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> Foo.delete('abc')
static sanitize_id(id)

Validate the given document id to make sure it’ll be supported by CouchDB, and encode as UTF-8. If the id is not compliant, a chula.nosql.couch.InvalidCouchdbDocumentIdError will be raised.

Parameters:id (str) – Proposed CouchDB document id
Return type:UTF-8 encoded str
>>> from chula.nosql import couch
>>> couch.Document.sanitize_id('abc')
'abc'

Documents

class chula.nosql.couch.Documents([db_conn=None, document=None, server=None, shard=None, track_dirty=None])

CouchDB document abstraction class (plural)

__init__(server=None, shard=None)
Parameters:
  • server (str) – Database server to use
  • shard (str) – Database shard to use
Return type:

None

>>> from chula.nosql import couch
>>>
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> # Now create the plural version of the class
>>> class Foos(couch.Documents):
...     DB = Foo.DB
query(func, cls=None, **kwargs)

Fetch from CouchDB using an inline query. This is very expensive as the query is compiled on every request. Only use this for development or debugging. When the query is ready, create a view out of it for far improved performance.

Parameters:
  • func (str (javascript function)) – CouchDB view name
  • limit (int) – Maximum number of documents to return
  • startkey (list) – CouchDB view key starting position
  • cls (type) – Class to fill for each document returned by the query
  • shard (str) – Database shard to use
Return type:

list of chula.nosql.couch.Document or subclass of it

>>> from chula.nosql import couch
>>>
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> # Now create the plural version of the class
>>> class Foos(couch.Documents):
...     DB = Foo.DB
>>>
>>> # Create our javascript query function
>>> query = "function(doc) { emit(null, doc);}"
>>>
>>> # Test our shiney adhoc query
>>> docs = Foos().query(query, cls=Foo)
>>> doc = docs.pop()
>>> doc.keys()
['new_key', '_rev', '_id', 'modified', 'created']
>>>
>>> # A few handy keyword args
>>> foos = Foos()
>>> docs = foos.query(query, cls=Foo, limit=3, descending=True)
>>> len(docs)
3
view(name, cls=None, **kwargs)

Fetch from a CouchDB view. Views are by default optimized for write performance, thus the first fetch can be slow if data has recently changed.

Parameters:
  • name (str) – CouchDB view name
  • descending (bool) – Sort descending (sorted by view key)
  • limit (int) – Maximum number of documents to return
  • startkey (list) – CouchDB view key starting position
  • cls (type) – Class to fill for each document returned by the view
  • shard (str) – Database shard to use
Return type:

list of chula.nosql.couch.Document or subclass of it

>>> from chula.nosql import couch
>>>
>>> class Foo(couch.Document):
...     DB = 'foo'
>>>
>>> # Now create the plural version of the class
>>> class Foos(couch.Documents):
...     DB = Foo.DB
>>>
>>> # First let's fetch using a builtin couch view
>>> docs = Foos().view('_all_docs', cls=Foo)
>>> len(docs) > 1
True
>>> doc = docs.pop()
>>>
>>> # A few handy keyword args
>>> foos = Foos()
>>> docs = foos.view('_all_docs', cls=Foo, limit=4, descending=True)
>>> len(docs)
4

Helper functions

chula.nosql.couch.connect(db[, shard=None, server=None])

Obtain a connection to a CouchDB server.

Parameters:
  • db (str) – Database to connect to
  • shard (str) – Database shard to use
  • server (str) – Database server to use
Return type:

couchdb.client.Server

Note

The server lookup is in the following order, first match wins:

  1. Value of the server keyword arg.
  2. CHULA_COUCHDB_SERVER env variable if set.
  3. http://localhost:5984 as a last resort.

Warning

CouchDB does not support upper case letters in database names. This might save you time :)

http://wiki.apache.org/couchdb/HTTP_database_API

Table Of Contents

Previous topic

chula.json – Wrapper for json support

Next topic

chula.webservice – Webservice helper module

This Page