couchdb Package

couchdb Package

client Module

Python client API for CouchDB.

>>> server = Server()
>>> db = server.create('python-tests')
>>> doc_id, doc_rev = db.save({'type': 'Person', 'name': 'John Doe'})
>>> doc = db[doc_id]
>>> doc['type']
'Person'
>>> doc['name']
'John Doe'
>>> del db[doc.id]
>>> doc.id in db
False
>>> del server['python-tests']
class cbtestlib.couchdb.client.Server(url='http://localhost:5984/', full_commit=True, session=None)

Bases: object

Representation of a CouchDB server.

>>> server = Server()

This class behaves like a dictionary of databases. For example, to get a list of database names on the server, you can simply iterate over the server object.

New databases can be created using the create method:

>>> db = server.create('python-tests')
>>> db
<Database 'python-tests'>

You can access existing databases using item access, specifying the database name as the key:

>>> db = server['python-tests']
>>> db.name
'python-tests'

Databases can be deleted using a del statement:

>>> del server['python-tests']
config()

The configuration of the CouchDB server.

The configuration is represented as a nested dictionary of sections and options from the configuration files of the server, or the default values for options that are not explicitly configured.

Return type:dict
create(name)

Create a new database with the given name.

Parameters:name – the name of the database
Returns:a Database object representing the created database
Return type:Database
Raises PreconditionFailed:
 if a database with that name already exists
delete(name)

Delete the database with the specified name.

Parameters:name – the name of the database
Raises ResourceNotFound:
 if a database with that name does not exist
Since :0.6
replicate(source, target, **options)

Replicate changes from the source database to the target database.

Parameters:
  • source – URL of the source database
  • target – URL of the target database
  • options – optional replication args, e.g. continuous=True
stats(name=None)

Server statistics.

Parameters:name – name of single statistic, e.g. httpd/requests (None – return all statistics)
tasks()

A list of tasks currently active on the server.

uuids(count=None)

Retrieve a batch of uuids

Parameters:count – a number of uuids to fetch (None – get as many as the server sends)
Returns:a list of uuids
version()

The version string of the CouchDB server.

Note that this results in a request being made, and can also be used to check for the availability of the server.

Return type:unicode
class cbtestlib.couchdb.client.Database(url, name=None, session=None)

Bases: object

Representation of a database on a CouchDB server.

>>> server = Server()
>>> db = server.create('python-tests')

New documents can be added to the database using the save() method:

>>> doc_id, doc_rev = db.save({'type': 'Person', 'name': 'John Doe'})

This class provides a dictionary-like interface to databases: documents are retrieved by their ID using item access

>>> doc = db[doc_id]
>>> doc                 
<Document '...'@... {...}>

Documents are represented as instances of the Row class, which is basically just a normal dictionary with the additional attributes id and rev:

>>> doc.id, doc.rev     
('...', ...)
>>> doc['type']
'Person'
>>> doc['name']
'John Doe'

To update an existing document, you use item access, too:

>>> doc['name'] = 'Mary Jane'
>>> db[doc.id] = doc

The save() method creates a document with a random ID generated by CouchDB (which is not recommended). If you want to explicitly specify the ID, you’d use item access just as with updating:

>>> db['JohnDoe'] = {'type': 'person', 'name': 'John Doe'}
>>> 'JohnDoe' in db
True
>>> len(db)
2
>>> del server['python-tests']
changes(**opts)

Retrieve a changes feed from the database.

Takes since, feed, heartbeat and timeout options.

cleanup()

Clean up old design document indexes.

Remove all unused index files from the database storage area.

Returns:a boolean to indicate successful cleanup initiation
Return type:bool
commit()

If the server is configured to delay commits, or previous requests used the special X-Couch-Full-Commit: false header to disable immediate commits, this method can be used to ensure that any non-committed changes are committed to physical storage.

compact(ddoc=None)

Compact the database or a design document’s index.

Without an argument, this will try to prune all old revisions from the database. With an argument, it will compact the index cache for all views in the design document specified.

Returns:a boolean to indicate whether the compaction was initiated successfully
Return type:bool
copy(src, dest)

Copy the given document to create a new document.

Parameters:
  • src – the ID of the document to copy, or a dictionary or Document object representing the source document.
  • dest – either the destination document ID as string, or a dictionary or Document instance of the document that should be overwritten.
Returns:

the new revision of the destination document

Return type:

str

Since :

0.6

create(data)

Create a new document in the database with a random ID that is generated by the server.

Note that it is generally better to avoid the create() method and instead generate document IDs on the client side. This is due to the fact that the underlying HTTP POST method is not idempotent, and an automatic retry due to a problem somewhere on the networking stack may cause multiple documents being created in the database.

To avoid such problems you can generate a UUID on the client side. Python (since version 2.5) comes with a uuid module that can be used for this:

from uuid import uuid4
doc_id = uuid4().hex
db[doc_id] = {'type': 'person', 'name': 'John Doe'}
Parameters:data – the data to store in the document
Returns:the ID of the created document
Return type:unicode
delete(doc)

Delete the given document from the database.

Use this method in preference over __del__ to ensure you’re deleting the revision that you had previously retrieved. In the case the document has been updated since it was retrieved, this method will raise a ResourceConflict exception.

>>> server = Server()
>>> db = server.create('python-tests')
>>> doc = dict(type='Person', name='John Doe')
>>> db['johndoe'] = doc
>>> doc2 = db['johndoe']
>>> doc2['age'] = 42
>>> db['johndoe'] = doc2
>>> db.delete(doc)
Traceback (most recent call last):
  ...
ResourceConflict: ('conflict', 'Document update conflict.')
>>> del server['python-tests']
Parameters:doc – a dictionary or Document object holding the document data
Raises ResourceConflict:
 if the document was updated in the database
Since :0.4.1
delete_attachment(doc, filename)

Delete the specified attachment.

Note that the provided doc is required to have a _rev field. Thus, if the doc is based on a view row, the view row would need to include the _rev field.

Parameters:
  • doc – the dictionary or Document object representing the document that the attachment belongs to
  • filename – the name of the attachment file
Since :

0.4.1

get(id, default=None, **options)

Return the document with the specified ID.

Parameters:
  • id – the document ID
  • default – the default value to return when the document is not found
Returns:

a Row object representing the requested document, or None if no document with the ID was found

Return type:

Document

get_attachment(id_or_doc, filename, default=None)

Return an attachment from the specified doc id and filename.

Parameters:
  • id_or_doc – either a document ID or a dictionary or Document object representing the document that the attachment belongs to
  • filename – the name of the attachment file
  • default – default value to return when the document or attachment is not found
Returns:

a file-like object with read and close methods, or the value of the default argument if the attachment is not found

Since :

0.4.1

info(ddoc=None)

Return information about the database or design document as a dictionary.

Without an argument, returns database information. With an argument, return information for the given design document.

The returned dictionary exactly corresponds to the JSON response to a GET request on the database or design document’s info URI.

Returns:a dictionary of database properties
Return type:dict
Since :0.4
list(name, view, **options)

Format a view using a ‘list’ function.

Parameters:
  • name – the name of the list function in the format designdoc/listname
  • view – the name of the view in the format designdoc/viewname
  • options – optional query string parameters
Returns:

(headers, body) tuple, where headers is a dict of headers returned from the list function and body is a readable file-like instance

multisave(docs, **options)

Perform a bulk insertion of the given documents.

name

The name of the database.

Note that this may require a request to the server unless the name has already been cached by the info() method.

Return type:basestring
purge(docs)

Perform purging (complete removing) of the given documents.

Uses a single HTTP request to purge all given documents. Purged documents do not leave any meta-data in the storage and are not replicated.

put_attachment(doc, content, filename=None, content_type=None)

Create or replace an attachment.

Note that the provided doc is required to have a _rev field. Thus, if the doc is based on a view row, the view row would need to include the _rev field.

Parameters:
  • doc – the dictionary or Document object representing the document that the attachment should be added to
  • content – the content to upload, either a file-like object or a string
  • filename – the name of the attachment file; if omitted, this function tries to get the filename from the file-like object passed as the content argument value
  • content_type – content type of the attachment; if omitted, the MIME type is guessed based on the file name extension
Since :

0.4.1

query(map_fun, reduce_fun=None, language='javascript', wrapper=None, **options)

Execute an ad-hoc query (a “temp view”) against the database.

>>> server = Server()
>>> db = server.create('python-tests')
>>> db['johndoe'] = dict(type='Person', name='John Doe')
>>> db['maryjane'] = dict(type='Person', name='Mary Jane')
>>> db['gotham'] = dict(type='City', name='Gotham City')
>>> map_fun = '''function(doc) {
...     if (doc.type == 'Person')
...         emit(doc.name, null);
... }'''
>>> for row in db.query(map_fun):
...     print row.key
John Doe
Mary Jane
>>> for row in db.query(map_fun, descending=True):
...     print row.key
Mary Jane
John Doe
>>> for row in db.query(map_fun, key='John Doe'):
...     print row.key
John Doe
>>> del server['python-tests']
Parameters:
  • map_fun – the code of the map function
  • reduce_fun – the code of the reduce function (optional)
  • language – the language of the functions, to determine which view server to use
  • wrapper – an optional callable that should be used to wrap the result rows
  • options – optional query string parameters
Returns:

the view reults

Return type:

ViewResults

revisions(id, **options)

Return all available revisions of the given document.

Parameters:id – the document ID
Returns:an iterator over Document objects, each a different revision, in reverse chronological order, if any were found
save(doc, **options)

Create a new document or update an existing document.

If doc has no _id then the server will allocate a random ID and a new document will be created. Otherwise the doc’s _id will be used to identity the document to create or update. Trying to update an existing document with an incorrect _rev will raise a ResourceConflict exception.

Note that it is generally better to avoid saving documents with no _id and instead generate document IDs on the client side. This is due to the fact that the underlying HTTP POST method is not idempotent, and an automatic retry due to a problem somewhere on the networking stack may cause multiple documents being created in the database.

To avoid such problems you can generate a UUID on the client side. Python (since version 2.5) comes with a uuid module that can be used for this:

from uuid import uuid4
doc = {'_id': uuid4().hex, 'type': 'person', 'name': 'John Doe'}
db.save(doc)
Parameters:
  • doc – the document to store
  • options – optional args, e.g. batch=’ok’
Returns:

(id, rev) tuple of the save document

Return type:

tuple

show(name, docid=None, **options)

Call a ‘show’ function.

Parameters:
  • name – the name of the show function in the format designdoc/showname
  • docid – optional ID of a document to pass to the show function.
  • options – optional query string parameters
Returns:

(headers, body) tuple, where headers is a dict of headers returned from the show function and body is a readable file-like instance

update(documents, **options)

Perform a bulk update or insertion of the given documents using a single HTTP request.

>>> server = Server()
>>> db = server.create('python-tests')
>>> for doc in db.update([
...     Document(type='Person', name='John Doe'),
...     Document(type='Person', name='Mary Jane'),
...     Document(type='City', name='Gotham City')
... ]):
...     print repr(doc) 
(True, '...', '...')
(True, '...', '...')
(True, '...', '...')
>>> del server['python-tests']

The return value of this method is a list containing a tuple for every element in the documents sequence. Each tuple is of the form (success, docid, rev_or_exc), where success is a boolean indicating whether the update succeeded, docid is the ID of the document, and rev_or_exc is either the new document revision, or an exception instance (e.g. ResourceConflict) if the update failed.

If an object in the documents list is not a dictionary, this method looks for an items() method that can be used to convert the object to a dictionary. Effectively this means you can also use this method with mapping.Document objects.

Parameters:documents – a sequence of dictionaries or Document objects, or objects providing a items() method that can be used to convert them to a dictionary
Returns:an iterable over the resulting documents
Return type:list
Since :version 0.2
update_doc(name, docid=None, **options)

Calls server side update handler.

Parameters:
  • name – the name of the update handler function in the format designdoc/updatename.
  • docid – optional ID of a document to pass to the update handler.
  • options – optional query string parameters.
Returns:

(headers, body) tuple, where headers is a dict of headers returned from the list function and body is a readable file-like instance

view(name, wrapper=None, **options)

Execute a predefined view.

>>> server = Server()
>>> db = server.create('python-tests')
>>> db['gotham'] = dict(type='City', name='Gotham City')
>>> for row in db.view('_all_docs'):
...     print row.id
gotham
>>> del server['python-tests']
Parameters:
  • name – the name of the view; for custom views, use the format design_docid/viewname, that is, the document ID of the design document and the name of the view, separated by a slash
  • wrapper – an optional callable that should be used to wrap the result rows
  • options – optional query string parameters
Returns:

the view results

Return type:

ViewResults

class cbtestlib.couchdb.client.Document

Bases: dict

Representation of a document in the database.

This is basically just a dictionary with the two additional properties id and rev, which contain the document ID and revision, respectively.

id

The document ID.

Return type:basestring
rev

The document revision.

Return type:basestring
class cbtestlib.couchdb.client.ViewResults(view, options)

Bases: object

Representation of a parameterized view (either permanent or temporary) and the results it produces.

This class allows the specification of key, startkey, and endkey options using Python slice notation.

>>> server = Server()
>>> db = server.create('python-tests')
>>> db['johndoe'] = dict(type='Person', name='John Doe')
>>> db['maryjane'] = dict(type='Person', name='Mary Jane')
>>> db['gotham'] = dict(type='City', name='Gotham City')
>>> map_fun = '''function(doc) {
...     emit([doc.type, doc.name], doc.name);
... }'''
>>> results = db.query(map_fun)

At this point, the view has not actually been accessed yet. It is accessed as soon as it is iterated over, its length is requested, or one of its rows, total_rows, or offset properties are accessed:

>>> len(results)
3

You can use slices to apply startkey and/or endkey options to the view:

>>> people = results[['Person']:['Person','ZZZZ']]
>>> for person in people:
...     print person.value
John Doe
Mary Jane
>>> people.total_rows, people.offset
(3, 1)

Use plain indexed notation (without a slice) to apply the key option. Note that as CouchDB makes no claim that keys are unique in a view, this can still return multiple rows:

>>> list(results[['City', 'Gotham City']])
[<Row id='gotham', key=['City', 'Gotham City'], value='Gotham City'>]
>>> del server['python-tests']
offset

The offset of the results from the first row in the view.

This value is 0 for reduce views.

Return type:int
rows

The list of rows returned by the view.

Return type:list
total_rows

The total number of rows in this view.

This value is None for reduce views.

Return type:int or NoneType for reduce views
class cbtestlib.couchdb.client.Row

Bases: dict

Representation of a row as returned by database views.

doc

The associated document for the row. This is only present when the view was accessed with include_docs=True as a query parameter, otherwise this property will be None.

error
id

The associated Document ID if it exists. Returns None when it doesn’t (reduce results).

key
value

design Module

Utility code for managing design documents.

class cbtestlib.couchdb.design.ViewDefinition(design, name, map_fun, reduce_fun=None, language='javascript', wrapper=None, options=None, **defaults)

Bases: object

Definition of a view stored in a specific design document.

An instance of this class can be used to access the results of the view, as well as to keep the view definition in the design document up to date with the definition in the application code.

>>> from couchdb import Server
>>> server = Server()
>>> db = server.create('python-tests')
>>> view = ViewDefinition('tests', 'all', '''function(doc) {
...     emit(doc._id, null);
... }''')
>>> view.get_doc(db)

The view is not yet stored in the database, in fact, design doc doesn’t even exist yet. That can be fixed using the sync method:

>>> view.sync(db)
>>> design_doc = view.get_doc(db)
>>> design_doc                                          
<Document '_design/tests'@'...' {...}>
>>> print design_doc['views']['all']['map']
function(doc) {
    emit(doc._id, null);
}

If you use a Python view server, you can also use Python functions instead of code embedded in strings:

>>> def my_map(doc):
...     yield doc['somekey'], doc['somevalue']
>>> view = ViewDefinition('test2', 'somename', my_map, language='python')
>>> view.sync(db)
>>> design_doc = view.get_doc(db)
>>> design_doc                                          
<Document '_design/test2'@'...' {...}>
>>> print design_doc['views']['somename']['map']
def my_map(doc):
    yield doc['somekey'], doc['somevalue']

Use the static sync_many() method to create or update a collection of views in the database in an atomic and efficient manner, even across different design documents.

>>> del server['python-tests']
get_doc(db)

Retrieve and return the design document corresponding to this view definition from the given database.

Parameters:db – the Database instance
Returns:a client.Document instance, or None if the design document does not exist in the database
Return type:Document
sync(db)

Ensure that the view stored in the database matches the view defined by this instance.

Parameters:db – the Database instance
static sync_many(db, views, remove_missing=False, callback=None)

Ensure that the views stored in the database that correspond to a given list of ViewDefinition instances match the code defined in those instances.

This function might update more than one design document. This is done using the CouchDB bulk update feature to ensure atomicity of the operation.

Parameters:
  • db – the Database instance
  • views – a sequence of ViewDefinition instances
  • remove_missing – whether views found in a design document that are not found in the list of ViewDefinition instances should be removed
  • callback – a callback function that is invoked when a design document gets updated; the callback gets passed the design document as only parameter, before that doc has actually been saved back to the database

http Module

Simple HTTP client implementation based on the httplib module in the standard library.

exception cbtestlib.couchdb.http.HTTPError

Bases: exceptions.Exception

Base class for errors based on HTTP status codes >= 400.

exception cbtestlib.couchdb.http.PreconditionFailed

Bases: cbtestlib.couchdb.http.HTTPError

Exception raised when a 412 HTTP error is received in response to a request.

exception cbtestlib.couchdb.http.ResourceNotFound

Bases: cbtestlib.couchdb.http.HTTPError

Exception raised when a 404 HTTP error is received in response to a request.

exception cbtestlib.couchdb.http.ResourceConflict

Bases: cbtestlib.couchdb.http.HTTPError

Exception raised when a 409 HTTP error is received in response to a request.

exception cbtestlib.couchdb.http.ServerError

Bases: cbtestlib.couchdb.http.HTTPError

Exception raised when an unexpected HTTP error is received in response to a request.

exception cbtestlib.couchdb.http.Unauthorized

Bases: cbtestlib.couchdb.http.HTTPError

Exception raised when the server requires authentication credentials but either none are provided, or they are incorrect.

exception cbtestlib.couchdb.http.RedirectLimit

Bases: exceptions.Exception

Exception raised when a request is redirected more often than allowed by the maximum number of redirections.

class cbtestlib.couchdb.http.Session(cache=None, timeout=None, max_redirects=5, retry_delays=[0], retryable_errors=frozenset([32, 100, 101, 102, 103, 104, 110, 111, 112, 113]))

Bases: object

request(method, url, body=None, headers=None, credentials=None, num_redirects=0)
class cbtestlib.couchdb.http.Resource(url, session, headers=None)

Bases: object

delete(path=None, headers=None, **params)
delete_json(*a, **k)
get(path=None, headers=None, **params)
get_json(*a, **k)
head(path=None, headers=None, **params)
post(path=None, body=None, headers=None, **params)
post_json(*a, **k)
put(path=None, body=None, headers=None, **params)
put_json(*a, **k)

json Module

Thin abstraction layer over the different available modules for decoding and encoding JSON data.

This module currently supports the following JSON modules:

The default behavior is to use simplejson if installed, and otherwise fallback to the standard library module. To explicitly tell CouchDB-Python which module to use, invoke the use() function with the module name:

from couchdb import json
json.use('cjson')

In addition to choosing one of the above modules, you can also configure CouchDB-Python to use custom decoding and encoding functions:

from couchdb import json
json.use(decode=my_decode, encode=my_encode)
cbtestlib.couchdb.json.decode(string)

Decode the given JSON string.

Parameters:string (basestring) – the JSON string to decode
Returns:the corresponding Python data structure
Return type:object
cbtestlib.couchdb.json.encode(obj)

Encode the given object as a JSON string.

Parameters:obj (object) – the Python data structure to encode
Returns:the corresponding JSON string
Return type:basestring
cbtestlib.couchdb.json.use(module=None, decode=None, encode=None)

Set the JSON library that should be used, either by specifying a known module name, or by providing a decode and encode function.

The modules “simplejson”, “cjson”, and “json” are currently supported for the module parameter.

If provided, the decode parameter must be a callable that accepts a JSON string and returns a corresponding Python data structure. The encode callable must accept a Python data structure and return the corresponding JSON string. Exceptions raised by decoding and encoding should be propagated up unaltered.

Parameters:
  • module (str or module) – the name of the JSON library module to use, or the module object itself
  • decode (callable) – a function for decoding JSON strings
  • encode (callable) – a function for encoding objects as JSON strings

mapping Module

Mapping from raw JSON data structures to Python objects and vice versa.

>>> from couchdb import Server
>>> server = Server()
>>> db = server.create('python-tests')

To define a document mapping, you declare a Python class inherited from Document, and add any number of Field attributes:

>>> from couchdb.mapping import TextField, IntegerField, DateField
>>> class Person(Document):
...     name = TextField()
...     age = IntegerField()
...     added = DateTimeField(default=datetime.now)
>>> person = Person(name='John Doe', age=42)
>>> person.store(db) 
<Person ...>
>>> person.age
42

You can then load the data from the CouchDB server through your Document subclass, and conveniently access all attributes:

>>> person = Person.load(db, person.id)
>>> old_rev = person.rev
>>> person.name
u'John Doe'
>>> person.age
42
>>> person.added                
datetime.datetime(...)

To update a document, simply set the attributes, and then call the store() method:

>>> person.name = 'John R. Doe'
>>> person.store(db)            
<Person ...>

If you retrieve the document from the server again, you should be getting the updated data:

>>> person = Person.load(db, person.id)
>>> person.name
u'John R. Doe'
>>> person.rev != old_rev
True
>>> del server['python-tests']
class cbtestlib.couchdb.mapping.Mapping(**values)

Bases: object

classmethod build(**d)
get(name, default=None)
setdefault(name, default)
unwrap()
classmethod wrap(data)
class cbtestlib.couchdb.mapping.Document(id=None, **values)

Bases: cbtestlib.couchdb.mapping.Mapping

id

The document ID

items()

Return the fields as a list of (name, value) tuples.

This method is provided to enable easy conversion to native dictionary objects, for example to allow use of mapping.Document instances with client.Database.update.

>>> class Post(Document):
...     title = TextField()
...     author = TextField()
>>> post = Post(id='foo-bar', title='Foo bar', author='Joe')
>>> sorted(post.items())
[('_id', 'foo-bar'), ('author', u'Joe'), ('title', u'Foo bar')]
Returns:a list of (name, value) tuples
classmethod load(db, id)

Load a specific document from the given database.

Parameters:
  • db – the Database object to retrieve the document from
  • id – the document ID
Returns:

the Document instance, or None if no document with the given ID was found

classmethod query(db, map_fun, reduce_fun, language='javascript', **options)

Execute a CouchDB temporary view and map the result values back to objects of this mapping.

Note that by default, any properties of the document that are not included in the values of the view will be treated as if they were missing from the document. If you want to load the full document for every row, set the include_docs option to True.

rev

The document revision.

Return type:basestring
store(db)

Store the document in the given database.

classmethod view(db, viewname, **options)

Execute a CouchDB named view and map the result values back to objects of this mapping.

Note that by default, any properties of the document that are not included in the values of the view will be treated as if they were missing from the document. If you want to load the full document for every row, set the include_docs option to True.

cbtestlib.couchdb.mapping.Field

Basic unit for mapping a piece of data between Python and JSON.

Instances of this class can be added to subclasses of Document to describe the mapping of a document.

cbtestlib.couchdb.mapping.TextField

Mapping field for string values.

cbtestlib.couchdb.mapping.FloatField

Mapping field for float values.

cbtestlib.couchdb.mapping.IntegerField

Mapping field for integer values.

cbtestlib.couchdb.mapping.LongField

Mapping field for long integer values.

cbtestlib.couchdb.mapping.BooleanField

Mapping field for boolean values.

cbtestlib.couchdb.mapping.DecimalField

Mapping field for decimal values.

cbtestlib.couchdb.mapping.DateField

Mapping field for storing dates.

>>> field = DateField()
>>> field._to_python('2007-04-01')
datetime.date(2007, 4, 1)
>>> field._to_json(date(2007, 4, 1))
'2007-04-01'
>>> field._to_json(datetime(2007, 4, 1, 15, 30))
'2007-04-01'
cbtestlib.couchdb.mapping.DateTimeField

Mapping field for storing date/time values.

>>> field = DateTimeField()
>>> field._to_python('2007-04-01T15:30:00Z')
datetime.datetime(2007, 4, 1, 15, 30)
>>> field._to_json(datetime(2007, 4, 1, 15, 30, 0, 9876))
'2007-04-01T15:30:00Z'
>>> field._to_json(date(2007, 4, 1))
'2007-04-01T00:00:00Z'
cbtestlib.couchdb.mapping.TimeField

Mapping field for storing times.

>>> field = TimeField()
>>> field._to_python('15:30:00')
datetime.time(15, 30)
>>> field._to_json(time(15, 30))
'15:30:00'
>>> field._to_json(datetime(2007, 4, 1, 15, 30))
'15:30:00'
cbtestlib.couchdb.mapping.DictField

Field type for nested dictionaries.

>>> from couchdb import Server
>>> server = Server()
>>> db = server.create('python-tests')
>>> class Post(Document):
...     title = TextField()
...     content = TextField()
...     author = DictField(Mapping.build(
...         name = TextField(),
...         email = TextField()
...     ))
...     extra = DictField()
>>> post = Post(
...     title='Foo bar',
...     author=dict(name='John Doe',
...                 email='john@doe.com'),
...     extra=dict(foo='bar'),
... )
>>> post.store(db) 
<Post ...>
>>> post = Post.load(db, post.id)
>>> post.author.name
u'John Doe'
>>> post.author.email
u'john@doe.com'
>>> post.extra
{'foo': 'bar'}
>>> del server['python-tests']
cbtestlib.couchdb.mapping.ListField

Field type for sequences of other fields.

>>> from couchdb import Server
>>> server = Server()
>>> db = server.create('python-tests')
>>> class Post(Document):
...     title = TextField()
...     content = TextField()
...     pubdate = DateTimeField(default=datetime.now)
...     comments = ListField(DictField(Mapping.build(
...         author = TextField(),
...         content = TextField(),
...         time = DateTimeField()
...     )))
>>> post = Post(title='Foo bar')
>>> post.comments.append(author='myself', content='Bla bla',
...                      time=datetime.now())
>>> len(post.comments)
1
>>> post.store(db) 
<Post ...>
>>> post = Post.load(db, post.id)
>>> comment = post.comments[0]
>>> comment['author']
'myself'
>>> comment['content']
'Bla bla'
>>> comment['time'] 
'...T...Z'
>>> del server['python-tests']
cbtestlib.couchdb.mapping.ViewField

Descriptor that can be used to bind a view definition to a property of a Document class.

>>> class Person(Document):
...     name = TextField()
...     age = IntegerField()
...     by_name = ViewField('people', '''\
...         function(doc) {
...             emit(doc.name, doc);
...         }''')
>>> Person.by_name
<ViewDefinition '_design/people/_view/by_name'>
>>> print Person.by_name.map_fun
function(doc) {
    emit(doc.name, doc);
}

That property can be used as a function, which will execute the view.

>>> from couchdb import Database
>>> db = Database('python-tests')
>>> Person.by_name(db, count=3)
<ViewResults <PermanentView '_design/people/_view/by_name'> {'count': 3}>

The results produced by the view are automatically wrapped in the Document subclass the descriptor is bound to. In this example, it would return instances of the Person class. But please note that this requires the values of the view results to be dictionaries that can be mapped to the mapping defined by the containing Document class. Alternatively, the include_docs query option can be used to inline the actual documents in the view results, which will then be used instead of the values.

If you use Python view functions, this class can also be used as a decorator:

>>> class Person(Document):
...     name = TextField()
...     age = IntegerField()
...
...     @ViewField.define('people')
...     def by_name(doc):
...         yield doc['name'], doc
>>> Person.by_name
<ViewDefinition '_design/people/_view/by_name'>
>>> print Person.by_name.map_fun
def by_name(doc):
    yield doc['name'], doc

multipart Module

Support for streamed reading and writing of multipart MIME content.

cbtestlib.couchdb.multipart.read_multipart(fileobj, boundary=None)

Simple streaming MIME multipart parser.

This function takes a file-like object reading a MIME envelope, and yields a (headers, is_multipart, payload) tuple for every part found, where headers is a dictionary containing the MIME headers of that part (with names lower-cased), is_multipart is a boolean indicating whether the part is itself multipart, and payload is either a string (if is_multipart is false), or an iterator over the nested parts.

Note that the iterator produced for nested multipart payloads MUST be fully consumed, even if you wish to skip over the content.

Parameters:
  • fileobj – a file-like object
  • boundary – the part boundary string, will generally be determined automatically from the headers of the outermost multipart envelope
Returns:

an iterator over the parts

Since :

0.5

cbtestlib.couchdb.multipart.write_multipart(fileobj, subtype='mixed', boundary=None)

Simple streaming MIME multipart writer.

This function returns a MultipartWriter object that has a few methods to control the nested MIME parts. For example, to write a flat multipart envelope you call the add(mimetype, content, [headers]) method for every part, and finally call the close() method.

>>> from StringIO import StringIO
>>> buf = StringIO()
>>> envelope = write_multipart(buf, boundary='==123456789==')
>>> envelope.add('text/plain', 'Just testing')
>>> envelope.close()
>>> print buf.getvalue().replace('\r\n', '\n')
Content-Type: multipart/mixed; boundary="==123456789=="

--==123456789==
Content-Length: 12
Content-MD5: nHmX4a6el41B06x2uCpglQ==
Content-Type: text/plain

Just testing
--==123456789==--

Note that an explicit boundary is only specified for testing purposes. If the boundary parameter is omitted, the multipart writer will generate a random string for the boundary.

To write nested structures, call the open([headers]) method on the respective envelope, and finish each envelope using the close() method:

>>> buf = StringIO()
>>> envelope = write_multipart(buf, boundary='==123456789==')
>>> part = envelope.open(boundary='==abcdefghi==')
>>> part.add('text/plain', 'Just testing')
>>> part.close()
>>> envelope.close()
>>> print buf.getvalue().replace('\r\n', '\n') #:doctest +ELLIPSIS
Content-Type: multipart/mixed; boundary="==123456789=="

--==123456789==
Content-Type: multipart/mixed; boundary="==abcdefghi=="

--==abcdefghi==
Content-Length: 12
Content-MD5: nHmX4a6el41B06x2uCpglQ==
Content-Type: text/plain

Just testing
--==abcdefghi==--
--==123456789==--
Parameters:
  • fileobj – a writable file-like object that the output should get written to
  • subtype – the subtype of the multipart MIME type (e.g. “mixed”)
  • boundary – the boundary to use to separate the different parts
Since :

0.6

view Module

Implementation of a view server for functions written in Python.

cbtestlib.couchdb.view.main()

Command-line entry point for running the view server.

cbtestlib.couchdb.view.run(input=<open file '<stdin>', mode 'r' at 0x7feb8d0fb0c0>, output=<open file '<stdout>', mode 'w' at 0x7feb8d0fb150>)

CouchDB view function handler implementation for Python.

Parameters:
  • input – the readable file-like object to read input from
  • output – the writable file-like object to write output to

Table Of Contents

Previous topic

couchbase Package

Next topic

membase Package

This Page