couchpy.database – CouchDB database interface

Database definition for accessing a CouchDB database. An instance of Database class corresponds to a single database in CouchDB server, and the object can be used to read, write, update its documents and query views. Also, Database objects provide pythonified way of accessing them.

Create a database,

>>> couch = Client()
>>> db = couch.put('contacts')             # Create
>>> db = couch.Database('contacts').put()  # Alternate way to create database
>>> db = couch.Database('contacts')        # Access database

Example list of operations that can be done with Database instance :

Get database information,

>>> db.info
{ ... }

Iterate over all documents in the database. Each iteration instance will yield couchpy.doc.Document object.

>>> docs = [ doc for doc in db ]

Access database as a dictionary of documents,

>>> db[u'011b9da9723dea64c645554bcf0261619efd68a1']
<Document u'011b9da9723dea64c645554bcf0261619efd68a1':u'1-16565128019675206d77f6836039af0e'>
>>> u'011b9da9723dea64c645554bcf0261619efd68a1' in db
True
>>> del db[u'011b9da9723dea64c645554bcf0261619efd68a1']     # Delete document
>>> len(db)   # Count of documents stored in the database,
>>> bool( db )  # Is database available.

Delete database,

>>> db.delete()

Track changes done to database, changes() methods accept a whole bunch of keyword arguments that are accepted as query arguments to DB API.

>>> db.changes()

Compact database, if optional argument designdoc is specified, all views associated with design-doc will be compacted.

>>> db.compact()
>>> db.compact(designdoc='views')

View cleanup,

>>> db.viewcleanup()

Ensure full commit,

>>> db.ensurefullcommit()

Bulk document inserts,

>>> docs = [ {'fruit' : 'orange'}, {'fruit' : 'apple'} ]
>>> db.bulkdocs( docs )
>>> db.bulkdocs( docs, atomic=True )

Get / Set security object,

>>> db.security({ "admins" : { "names" : ["joe"] } })
>>> db.security()
{u'admins': {u'names': [u'pratap']}}

Get / Set revs_limit

>>> db.revslimit( 122 )
>>> db.revslimit()
122

Module Contents

class couchpy.database.Database(client, dbname, hthdrs={}, **kwargs)

Instantiate the database object corresponding to dbname in CouchdDB server via client interface. Client’s connection will be used for all database access.

Optional arguments :

hthdrs,
Dictionary of HTTP request headers, remembered at the instance level. All http-requests made via this instance will use hthdrs for request headers. Aside from these headers, if an instance method supports hthdrs key-word argument, it will override instance-level request-headers.
static __new__(client, dbname, **kwargs)

Database factory providing singleton pattern for Database objects. Database instance are cached under the client object, and every instantiation

>>> a = Database( 'dbname' )
>>> b = Database( 'dbname' )

a and b will point to the same object.

__call__()

Return information about this database, refer to GET /db API from CouchDB reference manual to know the structure of information. Every time the object is called, database information will be fetched from the server. For efficiency reasons, access database information via info attribute, which will fetch the information only once and cache them for subsequent use.

Admin-Prev: No

__iter__()

Iterate over all documents in this database. For every iteration, couchpy.doc.Document value will be yielded.

Admin-prev: No

__getitem__(key)

Return a couchpy.doc.Document instance, for the document specified by key which is document’s _id.

Admin-prev: No

__len__()

Return number of documents in the database.

Admin-prev: No

__nonzero__()

Return a Boolean, on database availability in the server. Python way of bool-check for Database.ispresent()

__delitem__(docid)

Remove the document specified by docid from database

__contains__(docid)

Return whether the document identified by docid is present in the database.

ispresent()

Boolean, whether database is present in the server.

changes(hthdrs={}, callback=None, **query)

Obtain a list of changes done to the database. This can be used to monitor modifications done on the database for post processing or synchronization. Returns JSON converted changes objects, and the last update sequence number, as returned by CouchDB. Refer to GET /<db>/_changes API for more information.

Optional key-word arguments

callback,
callback function accepting a single argument line for every line of change notification as JSON string. This argument is valid only for feed=continuous. In continuous-mode, style and heartbeat query parameters are equally valid. Although callback function will be invoked for every notification line, changes() API method itself will block for-ever or until the heartbeat expires.

query key-word arguments,

feed,
Type of feed, longpoll | continuous | normal.
style,
Defines the structure of changes array for each row. Can be one of all_docs | main_only. all_docs will provide more revision and conflict information in the changes array for each result row. If you want to specify the default explicitly, the value is main_only.
filter,
Filter changes using a filter function defined in the design document.
heartbeat,
Period in milliseconds, after which an empty line is sent during longpoll or continuous.
include_docs,
A string value of either true or false. If true, include the document with the result.
limit,
Maximum number of rows to return.
since,
Start the results from the specified sequence number.
timeout,
Maximum period in milliseconds to wait before the response is sent.

Admin-prev: No

compact(designdoc=None, hthdrs={})

Request compaction for this database. Compaction compresses the disk database file by performing the following operations.

  • Writes a new version of the database file, removing any unused sections from the new version during write. Because a new file is temporarily created for this purpose, you will need twice the current storage space of the specified database in order for the compaction routine to complete.
  • Removes old revisions of documents from the database, up to the per-database limit specified by the _revs_limit database parameter.

Alternatively, you can specify the designdoc key-word argument to compact the view indexes associated with the specified design document. You can use this in place of the full database compaction if you know a specific set of view indexes have been affected by a recent database change.

Return JSON converted object as returned by CouchDB, refer to POST /<db>/_compact and POST /<db>/_compact>/<designdoc> APIs for more information.

Admin-prev: Yes

viewcleanup(hthdrs={})

Clean-up the cached view output on the disk.

Admin-prev: Yes

ensurefullcommit(hthdrs={})

Commit recent changes to disk. You should call this if you want to ensure that recent changes have been written. Return JSON converted object as returned by CouchDB.

Admin-prev: No

bulkdocs(docs=[], atomic=False, hthdrs={})

Bulk document API allows you to create and update multiple documents at the same time within a single request. The basic operation is similar to creating or updating a single document, except that you batch the document structure and information. When creating new documents the document ID is optional. For updating existing documents, you must provide the document ID, revision information, and new document values.

You can optionally delete documents during a bulk update by adding the _deleted field with a value of true to each document ID/revision combination within the submitted JSON structure. Which is what bulkdelete() API method does.

docs contains a list of couchpy.doc.Document instances or dictionaries. In case of couchpy.doc.Document instance, the object instance will be updated with the new revision number.

To perform document updates and inserts atomically, pass atomic keyword as True.

Returns JSON converted return value for CouchDB API /db/_bulk_docs

Admin-prev: No

bulkdelete(docs=[], atomic=False, hthdrs={})

Same as Database.bulkdocs() except that the _delete property in each document will be set to True, thus deleting the documents from the database. To delete the documents in atomic fashion, pass keyword parameter atomic as True.

Returns JSON converted return value for CouchDB API /db/_bulk_docs

tempview(designdoc, hthdrs={}, **query)

Create (and execute) a temporary view based on the view function supplied in the JSON request. This API accepts the same query parameters supported by _view API. Returns JSON converted object as returned by CouchdB. Refer to POST /<db>/_temp_view and GET  /<db>/_design/<design-doc>/_view/<view-name> sections in CouchDB API reference manual for more information.

Admin-prev: Yes

purge(docs, hthdrs={})

A database purge permanently removes the references to deleted documents from the database. Deleting a document within CouchDB does not actually remove the document from the database, instead, the document is marked as deleted (and a new revision is created). This is to ensure that deleted documents are replicated to other databases as having been deleted. The purging of old documents is not replicated to other databases. Purging documents does not remove the space used by them on disk. To reclaim disk space, you should run a database compact operation.

Either pass a JSON convertible object that will be directly sent as request body or, pass a list of documents where each element of the list can be a document dictionary or couchpy.doc.Document object.

Returns JSON converted object as returned by CouchDB API /db/_purge

>>> d = { "FishStew" : [ "17-b3eb5ac6fbaef4428d712e66483dcb79" ] }
>>> db.purge( d )
>>> docs = db.all_docs()
>>> db.purge( docs )

Admin-prev: Yes

all_docs(keys=None, hthdrs={}, q={}, **params)

Return a JSON structure of all of the documents in a given database. The information is returned as a JSON structure containing meta information about the return structure, and the list documents and basic contents, consisting the ID, revision and key. The key is generated from the document ID. Refer to POST /<db>/_all_docs from CouchDB API manual for more information, like default values, for unspecified query parameters.

If optional key-word argument keys is passed, specifying a list of document ids, only those documents will be fetched and returned.

query parameters are similar to that of views.

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.

Alternately, query parameters can be passed as a dictionary or Query object to key-word argument _q.

The ‘skip’ option should only be used with small values, as skipping a large range of documents this way is inefficient

Admin-prev: No

missingrevs()

TBD : To be implemented

revsdiff()

TBD : To be implemented

security(security=None, hthdrs={})

Get or Set the current security object for this database. The security object consists of two compulsory elements, admins and readers, which are used to specify the list of users and/or roles that have admin and reader rights to the database respectively. Any additional fields in the security object are optional. The entire security object is made available to validation and other internal functions, so that the database can control and limit functionality.

To set current security object, pass them as key-word argument,

security,
Security object contains admins and readers

Return the current security object

Admin-prev: Yes for setting the security object

revslimit(limit=None, hthdrs={})

Get or Set the current revs_limit (revision limit) for database. To set revs_limit, pass the value as key-word argument limit

Admin-prev: Yes for setting the revision limit

put(hthdrs={})

Create a new database, corresponding to this instance. The database name must adhere to the following rules.

  • Name must begin with a lowercase letter
  • Contains lowercase characters (a-z)
  • Contains digits (0-9)
  • Contains any of the characters _, $, (, ), +, -, and /

Return, Database object

Admin-prev: Yes

delete(hthdrs={})

Delete the database from server, and all the documents and attachments contained within it.

Return, JSON converted object as returned by couchDB.

Admin-prev: Yes

fetch()

– TBD – This is part multi-document access design, which is still evolving.

Call to this method will bulk fetch all the active document that are yet to be fetched from the server.

commit()

– TBD – This is part multi-document access design, which is still evolving.

Call to this method will bulk commit all the active documents that are dirtied.

CouchPy

Table Of Contents

Previous topic

couchpy.client – CouchDB client

Next topic

couchpy.doc – CouchDB document interface

This Page