couchpy.doc – CouchDB document interface

CouchDB is a document database and documents are stored in JSON format. Fortunately, JSON formated objects can easily be converted to native python objects. Document class defines a collection of attributes and methods to access CouchDB documents.

>>> c = Client()
>>> db = c.create( 'testdb' )

Create a document by name Fishstew, with a list of files attached to it. files must be a list of filepaths.

>>> doc = { _id='Fishstew' }
>>> doc = db.Document.post( doc, attachfiles=files )
>>> doc1 = { _id='ChickenTikaa' }
>>> doc1 = db.Document.post( doc1, attachfiles=files, batch='ok' )

Fetch document,

>>> doc = Document( db, 'Fishstew' )               # Fetch latest revision
>>> doc = Document( db, 'Fishstew', rev=u'1-1eb6f37b091a143c69ed0332de74df0b' # Fetch a particular revision
>>> revs = Document( db, doc, revs=True )          # Fetch revision list
>>> revsinfo = Document( db, doc, revs_info=True ) # Fetch extended revisions

Document object is a dictionary mapping for JSON document’s (key,value) pair.

>>> doc['tag'] = 'seafood'      # Create / update a new field 
>>> doc['tag']                  # Access key, value pair
seafood

And there is a convenience feature to access document keys as Document object attributes. But nested dictionaries are accessed using dictionary-access syntax.

>>> doc._id                     # Document ID
Fishstew
>>> doc._rev                    # Document Revision
u'1-1eb6f37b091a143c69ed0332de74df0b'
>>> doc.items()                 # List of (key,value) pairs
[(u'_rev', u'1-1eb6f37b091a143c69ed0332de74df0b'), (u'_id', u'Fishstew'), (u'tag', u'seafood')]
>>> doc.update({ 'key1' : 'value1' })
>>> [ (k,v) for k,v in doc ]    # Same as doc.items()
>>> doc.delitem( 'key1' )       # Delete key,value pair
>>> del doc['key1']             # Same as doc.delitem

Manage document attachments,

>>> a = doc.addattach( '/home/user/recipe.txt' )  # Attach file to document
>>> doc.attachs()                                 # Get a list of Attachment objects
>>> a = doc.attach( 'recipe.txt' )
>>> a.filename                                    # Attachment filename 
recipe.txt
>>> a.data()
( ... file content ..., text/plain )
>>> doc.delattach( a )                            # Delete attachment

Delete document,

>>> Document.delete( db, doc1 )

Copy document,

>>> bkpdoc = Document.copy( db, doc._id, 'Fishstew-bkp', rev=doc._rev )

Module Contents

class couchpy.doc.StateMachine(doc)

State-machine for every document that is ever instantiated on the couchpy.database.Database object. CRUD operations on document object are abstracted into events and the document moves from one state to another based on events. Our purpose is to make sure that,

  • when ever a Document is instantiated in the same couchpy.database.Database context, the same document object must be emitted (singleton design pattern).
  • Typically during a web-request, a document might go through several side-effects. By having a clear state-machine, it is easier for couchpy to track the side-effects, optimize on server access and catch bugs.

The following special attributes are used on the document instance (ofcourse they are not persisted in server and the special attributes start with _x)

  • _x_smach, an instance of StateMachine
  • _x_state, document state, can be one of, ST_ACTIVE_INVALID, ST_ACTIVE_VALID, ST_ACTIVE_DIRTY, ST_ACTIVE_POST, ST_CACHE_INVALID.
  • _x_init, boolean indicates a fresh instance of Document is being created.
  • _x_reinit, boolean indicates that already a Document instance for this _id is in one of the active state, but needs to be presented as a freshly instantiated object.
  • _x_conn, couchpy.rest.ReSTful object.
  • _x_db, couchpy.database.Database object where document is stored.
  • _x_paths, list of path segments pointing to CouchDB’s document url.
  • _x_hthdrs, dictionary of http request headers to be used for document access.
  • _x_query, query params like rev, revs, revs_info.
class couchpy.doc.Document(db, doc, hthdrs={}, **query)

Document modeling.

Instantiate python representation of a CouchDB document. The resulting object is essentially a dictionary class. db should be couchpy.database.Database object, while doc can be one of the following, which will change the behavior of instantiation, along with rest of the arguments. If rev keyword argument is not passed, then latest document’s revision will be fetched from the server.

doc can be _id string,

In which case, document may or may not be present in the database. Unless otherwise a fetch() is done on the document object, it will be assumed as a fresh document to be inserted into database. Doing a subsequent post Document.post() will create a new document and doing a Document.fetch() will fetch the latest document revision.

doc can be dictionary,

if _id key and _rev key is present (which is the latest revision of the document), then the document instantiation behaves exactly the same way as if doc is _id string, and a fetch() call will get the document’s revision _rev from database.

if _id field is present but _rev field is not present, then it may or may not be present in the database. Unless otherwise a fetch() is done on the document object, it will be assumed as a fresh document to be inserted into database. Doing a subsequent post Document.post() will create a new document or doing a Document.fetch() will fetch the latest document revision.

If both _id and _rev keys are not present, then the document instance is presumed as a fresh document which needs to be created. The actual creation happens when Document.post() method is called, with its document _id automatically generated and updated into this object (long with its revision).

doc with rev keyword parameter,

Instantiation happens for an existing document’s older revision rev and the instance will be an immutable one. The only purpose for such instances are to fetch() the document from database and consume its content. No side-effects allowed.

Optional arguments:

hthdrs,
HTTP headers which will be remembered for all document access initiated via this object.
rev,
Specify document’s revision to fetch, will instantiate an immutable version of the document.
revs,
A string value of either true or false. If true, then, the document will include a revision list for this document. To learn more about the structure of the returned object, refer to GET /<db>/<doc> in CouchDB API manual.
revs_info,
A string value of either true or false. If true, then, the document will include extended revision list for this document. To learn more about the structure of the returned object, refer to GET /<db>/<doc> in CouchDB API manual.

Admin-prev: No

static __new__(db, doc, **kwargs)

Document instantiater. If _id is provided, the singleton object is looked up from ‘active’ list or ‘cached’ list. If doc is not present, a new Document is instantiated which will be saved in the ‘active’ list of the document _id is available. Sometimes, while creating a new document, the caller may not provide the _id value (DB will auto generate the ID). In those scenarios, the document instance will be added to the ‘active’ list after a Document.post() method is called.

changed()

Mark the document as changed. Use this method when document fields are updated indirectly (like nested lists and dictionaries), without using one of this document’s methods.

invalidate()

If by other means, it is found that the document is no longer the latest version (i.e) the database base version has moved forward, then programmatic-ally invalidate this document so that a side-effect operation will fetch them afresh from the database.

__getattr__(name)

Access document values as attributes of this instance.

__setattr__(name, value)

Set document values as attributes to this instance. Attributes starting with _x_ will be treated as special attributes and does not map to DB-Document’s attribute.

__setitem__(key, value)

Update DB-Document’s attributes as attributes of this object. Don’t forget to call Document.put() later.

__delitem__(key)

Delete key,value pair identified by key. Python shortcut for Document.delitem(). Don’t forge to call Document.put() later.

clear(special=False, _x_dirty=True)

Clear all attributes of the document. Equivalent of deleteing all key’s in this document object’s dictionary.

special,
Boolean, indicating whether to delete the special attributes that start with _ which are normally interpreted by CouchDB. Of-course there is no sense it trying to delete _id or _rev attributes.

Don’t forget to call Document.put() method later.

update(*args, **kwargs)

Maps to update() method of dictionary type. Don’t forget to call Document.put() method later.

setdefault(key, *args)

Maps to setdefault() method of dictionary type. Don’t forget to call Document.put() method later.

pop(key, *args)

Maps to pop() method of dictionary type. Don’t forget to call Document.put() method later.

popitem()

Maps to popitem() method of dictionary type. Don’t forget to call Document.put() method later.

__call__(hthdrs={}, **query)

Behaves like a factory method returning Document instances based on the keyword parameters

Optional keyword arguments:

hthdrs,
HTTP headers to be used for the document instance.
revs,
A string value of either true or false. If true, include revision information along with the document.
revs_info,
A string value of either true or false. If true, include extended revision information along with the document.
rev,
If specified, rev will be assumed as one of the previous revision of this document. An immutable version of document (ImmutableDocument) will be returned.

Admin-prev: No

head(hthdrs={}, **query)

HEAD method to check for the presence and latest revision of this document in the server.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.
rev,
Make the HEAD request for this document’s revision, rev
revs,
A string value of either true or false.
revs_info,
A string value of either true or false.

Return HTTP response header, the latest revision of the document is available as ETag value in response header.

Admin-prev: No

post(hthdrs={}, **query)

POST method on this document. To create or insert a new document into the database, create an instance of Document without specifying the _rev field and call this post method on the instance. If _id is not provided, CouchDB will auto generate an id value for the document and updated into this dictionary as well. New documents are not created until a call is made to this method.

Optional keyword parameters,

hthdrs,
Dictionary of HTTP headers for this HTTP request.
batch,
If specified ‘ok’, allow document store request to be batched with others. When using the batch mode, the document instance will not be updated with the latest revision number. A fetch() call is required to get the latest revision of the document.

Return the document with its _rev field updated to the latest revision number, along with the _id field.

Admin-prev: No

fetch(hthdrs={}, **query)

GET the document from disk. Always fetch the latest revision of the document. Documents are not fetched from the database until a call is made to this document.

Optional keyword parameters,

hthdrs,
Dictionary of HTTP headers for this HTTP request.
revs,
A string value of either true or false. If true, get the document with a list of all revisions on the disk.
revs_info,
A string value of either true or false. If true, get the document with a list of extended revision information.

Return this document object (useful for chaining calls).

Admin-prev: No

put(hthdrs={}, **query)

If the document instance is changed / modified, persist the changes in the server by calling this method. This method can be called only for documents that already exist in database. Documents are not updated (persisted) in the database, until a call is made to this method.

Optional keyword parameters,

batch,
if specified ‘ok’, allow document store request to be batched with others. When using the batch mode, the document instance will not be updated with the latest revision number. A fetch() call is required to get the latest revision of the document.

Return the document with its _rev field updated to the latest revision number.

Admin-prev: No

delete(hthdrs={}, rev=None)

Delete document from database. The document and its instance will no more be managed by CouchPy.

Optional keyword parameters,

rev,
Latest document revision. If not provided, then it is expected at self._rev

Return None.

Admin-prev: No

copy(toid, asrev=None, hthdrs={})

Copy this document to a new document, the source document’s id and revision will be interpreted from this object, while the destination’s id and revision must be specified as keyword arguments.

toid,
Destination document id
asrev,
Destination document’s latest revision

Return the copied document object

attach(filepath, content_type=None)

Use this method in conjuction with post(), that is for documents that are newly created. Something like,

>>> doc = db.Document( db, { '_id' : 'FishStew' } )
>>> doc.attach( '/home/user/readme.txt' ).post()
filepath,
Compute filename and file content from this.

optional keyword arguments,

content_type,
File’s content type.
class couchpy.doc.Attachment(doc, hthdrs={}, filename=None, filepath=None, **fields)

Represents a single attachment file present in the document, allows operations like put / get / delete of the attachment file under the document. Note that these methods are applicable only for documents that are already inserted (created) in the database. That is, Attachment object must be instantiated under a Document context. The natural way to do that is,

>>> doc = db.Document( db, { '_id' : 'FishStew' } ).fetch()
>>> doc.Attachment( filepath='/home/user/readme.txt' ).put()

Instances of attachments are also emitted by document objects like,

>>> doc = db.Document( db, { '_id' : 'FishStew' } ).fetch()
>>> attachs = doc.attachments() # List of `Attachment` objects

Add file specified by filepath as attachment to this document. HTTP headers ‘Content-Type’ and ‘Content-Length’ will also be remembered in the database. Optionally, content_type can be provided as key-word argument.

Return Attachment object.

Admin-prev: No

get(hthdrs={})

GET attachment from database. Attributes like, file_name, content_type, data are available on this object.

optional keyword arguments,

hthdrs,
HTTP headers for this HTTP request.

Admin-prev: No

put(hthdrs={})

Upload the attachment. Attachments are not added to the document until a call is made to this method. Uploading attachment will increment the revision number of the document, which will be automatically updated in the attachment’s document instance.

optional keyword arguments,

hthdrs,
HTTP headers for this HTTP request.

Admin-prev: No

delete(hthdrs={})

Delete the attachment file from the document. This will increment the revision number of the document, which will be automatically updated in the attachment’s document instance

optional keyword arguments,

hthdrs,
HTTP headers for this HTTP request.

Admin-prev: No

class couchpy.doc.LocalDocument(db, doc, hthdrs={}, **query)

Local documents have the following limitations: * Local documents are not replicated to other databases. * The ID of the local document must be known to access the document.

User cannot obtain a list of local documents from the database.
  • Local documents are not output by views, or the _all_docs API.

Note that LocalDocument class is not derived from Document class, it is derived from built-in dict.

Optional keyword arguments:

hthdrs,
HTTP headers which will be remembered for all database access initiated via this object.
rev,
Specify local document’s revision to fetch.
revs,
A string value of either true or false. If true, then, the document will include a revision list for this local document. To learn more about the structure of the returned object, refer to GET /<db>/<doc> in CouchDB API manual.
revs_info,
A string value of either true or false. If true, then, the document will include extended revision list for this local document. To learn more about the structure of the returned object, refer to GET /<db>/<doc> in CouchDB API manual

Admin-prev: No

__getattr__(name)

Access local document values as attributes of this instance.

__setattr__(name, value)

Set local document values as attributes to this instance

__call__(hthdrs={}, **query)

Behaves like a factory method generating LocalDocument instance based on the keyword arguments.

Optional keyword arguments:

hthdrs,
HTTP headers to be used for the document instance.
revs,
A string value of either true or false. If true, include revision information along with the document.
revs_info,
A string value of either true or false. If true, include extended revision information along with the document.
rev,
When fetching, return the local document for the requested revision.

Admin-prev: No

fetch(hthdrs={}, **query)

GET this local document from disk. Always fetch the latest revision of the document.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.
revs,
A string value of either true or false. If true, get the document with a list of all revisions on the disk.
revs_info,
A string value of either true or false. If true, get the document with a list of extended revision information.

Return this document object.

Admin-prev: No

put(hthdrs={}, **query)

Persist the local document on the disk.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.
batch,
if specified ‘ok’, allow document store request to be batched with others. When using the batch mode, the document instance will not be updated with the latest revision number. A fetch() call is required to get the latest revision of the document.

Return the document with its _rev field updated to the latest revision number.

Admin-prev: No

delete(hthdrs={}, rev=None)

Delete the local document from the database.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.
rev,
Latest document revision. If not provided, then it is expected at self._rev

Return None.

Admin-prev: No

copy(toid, asrev=None, hthdrs={})

Copy this local document to a new document, the source document’s id and revision will be interpreted from this object, while the destination’s id and revision must be specified via the keyword argument.

toid,
Destination document id
asrev,
Destination document’s latest revision. Right now the test cases show that copying to existing document fails. TODO

Return the copied document object

class couchpy.doc.ImmutableDocument(db, doc, hthdrs={}, rev=None, **query)

Immutable version of document objects, the document must be specified with _id and _rev. Users cannot change or modify the document contents. Unlike the Document objects, only ImmutableDocument.fetch() method is available.

Optional keyword arguments,

hthdrs,
HTTP headers for this HTTP request.
rev,
Specify document’s revision to fetch.
revs,
A string value of either true or false. If true, get the document with a list of all revisions on the disk.
revs_info,
A string value of either true or false. If true, get the document with a list of extended revision information.
__setattr__(name, value)

Not allowed

fetch(hthdrs={}, **query)

GET this document from disk. Fetch the document revision specified earlier.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.
revs,
A string value of either true or false. If true, get the document with a list of all revisions on the disk.
revs_info,
A string value of either true or false. If true, get the document with a list of extended revision information.

Returns this document object.

Admin-prev: No

class couchpy.doc.DesignDocument(*args, **kwargs)

Derived from Document class, encapsulates a design document stored in database. Initialization, creation and other operations are exactly similar to that of normal documents, except for the following additional details.

info(hthdrs={})

Return information on this design document. To know more about the information structure, refer to GET /<db>/_design/<design-doc>/_info CouchDB API manual.

Optional keyword parameters,

hthdrs,
HTTP headers for this HTTP request.

Admin-prev: Yes

views()

Return Views dictionary.

class couchpy.doc.Views(doc, views, *args, **kwargs)

Dictionary of views defined in design document doc. This object will be automatically instantiated by DesignDocument.views() method. Each view definition inside the design document is abstracted using View, which can be obtained from this dictionary as,

>>> designdoc = db.DesignDocument( 'userviews' ).fetch()
>>> userviews = designdoc.views()
>>> userviews['bypincode']
__setattr__(name, value)

Not allowed

class couchpy.doc.View(doc, viewname, view, hthdrs={}, q={})

Represents map,reduce logic for a single-design-document view. Some of the functions defined by this class are,

  • To allow user to query the view represented by this object.
  • To construct Document and ImmutableDocument objects based on the view’s return structures.
  • Create clones of this view object with pre-initialized query parameters.
doc,
design-document containing this view definition logic.
viewname,
name of this view, without the _view/ prefix.
hthdrs,
Dictionary of HTTP headers for all HTTP request made via this class instance. It will override hthdrs defined for the doc object.
q
A new set of query parameters as a dictionary or Query instance. The query parameters are explained in detail in Query.
__call__(hthdrs={}, _q={}, **params)

Create a clone of this view object with a different set of query parameters. A fresh instance obtained via Views does not contain any query parameters.

Optional key-word arguments,

hthdrs,
Dictionary of HTTP headers to be used for all request via cloned object.
_q,
Dictionary containing new set of query parameters to be remembered in the cloned object. The query parameters are explained in detail in Query.
**params
query parameters to be updated with existing set of query parameters from the cloned object.
fetch(keys=None, hthdrs={}, query={}, **params)

View query.

keys
If is None, then all the documents in the view index will be fetched.
hthdrs
Dictionary of HTTP headers for this HTTP request.
query
A new set of query parameters as dictionary or Query instance. The query parameters are explained in detail in Query.
params
A dictionary of query parameters to be updated on the existing query dictionary for this request.

Admin-prev: No

class couchpy.doc.Query(_q={}, **params)

Create a Query object using, keyword arguments which map to the view query parameters. Optionally, a dictionary of query parameters can be passed via the keyword argument _q. The query parameters are explained as,

descending,
A string value of either true or false. If true, return documents in descending key order.
endkey,
Stop returning records when the specified key is reached.
endkey_docid,
Stop returning records when the specified document ID is reached.
group,
A string value of either true or false. If true, group the results using the reduce function to a group or single row.
group_level,
Description Specify the group level to be used.
include_docs,
A string value of either true or false. If true, include the full content of the documents in the response.
inclusive_end,
A string value of either true or false. If true, includes specified end key in the result.
key,
Return only documents that match the specified key.
limit,
Limit the number of the returned documents to the specified number.
reduce,
A string value of either true or false. If true, use the reduction function.
skip,
Skip this number of records before starting to return the results.
stale,
Allow the results from a stale view to be used.
startkey,
Return records starting with the specified key
startkey_docid,
Return records starting with the specified document ID.
update_seq,
A string value of either true or false. If true, include the update sequence in the generated results.
__getattr__(name)

Access views attributes of this instance.

__setattr__(name, value)

Set query parameters as attributes to this instance

__repr__

x.__repr__() <==> repr(x)

__str__()

Construct url query string from key,value pairs and return the same.

CouchPy

Table Of Contents

Previous topic

couchpy.database – CouchDB database interface

Next topic

couchpy.utils – CouchDB utility functions

This Page