corduroy.
Couch

Represents a CouchDB server.

Useful for creating/deleting DBs and dealing with system-level functionality such as replication and task monitoring.

  • __init__ (url=None, auth=None, full_commit=True)

    Initialize the server object.

    Args

    • url (str): url of the couchdb server
    • auth (tuple): login information. e.g., ('username', 'password')

    Kwargs

    • full_commit (bool): include the X-Couch-Full-Commit header
  • all_dbs (callback=None)

    Retrieve the list of database names on this server

  • config (name=None, value=None, delete=False, callback=None)

    Get/set the configuration of the CouchDB server (or a field thereof).

    Args

    • name (str): optional path to a sub-field of the config dict
    • value (str,dict,int): optional new value for the path specified by name

    Kwargs

    • delete (bool): if true, delete the path speficied by name

    Returns

    • When called without a name arg, returns the entire config dictionary.
    • When name is specified, returns the value of that sub-path
    • When value is specified, returns None
    • When delete is specified, returns the pre-deletion value
  • create (name, callback=None)

    Create a new database with the given name.

    Args

    • name (str): The name of the database to create (without the server's url prefix)

    Returns

    • Database. An initialized Database object

    Raises

    • PreconditionFailed (if the database already exists)
  • db (name, create_if_missing=False, callback=None)

    Initialize a Database object corrsponding to a particular db name.

    Args

    • name (str): The name of the database (without the server's url prefix)
    • create_if_missing (bool): If true, will handle NotFound errors by creating the database specified by name

    Kwargs

    • create_if_missing (bool): if True, attempt to create the database if the initial request results in a NotFound

    Returns

    • Database. An initialized Database object

    Raises

    • NotFound (when database does not exists and create_if_missing==False)
  • delete (name, callback=None)

    Delete the database with the specified name.

    Args

    • name (str): The name of the database to delete

    Raises

    • NotFound (when database does not exists)
  • replicate (source, target, callback=None, **options)

    Replicate changes from the source database to the target database.

    Args

    • source (str, Database): either a full url to the source database (with authentication provided inline) or an initialized Database object
    • target (str, Database): the url or Database object of the target db

    Kwargs

    • _id (str): an optional replication_id. If provided, a doc will be created in the _replicator database for subsequent querying. If not provided, the legacy _replicate API will be used instead.
    • cancel (bool): if true, cancel the replication
    • continuous (bool): if True, set the replication to be continuous
    • create_target (bool): if True, creates the target database
    • doc_ids (list): optional list of document IDs to be synchronized
    • proxy (str): optional address of a proxy server to use
  • replicator ‹property›

    The _replicator system database

    Returns

    • Database. This property is a synonym for self.db('_replicator')
  • stats (name=None, callback=None)

    Server statistics.

    Args

    • name (str): optional sub-path of stats dict to return

    Returns

    • When called without args, returns the entire stats dictionary
    • When name is specified, returns the value at that sub-path

    Raises

    • NotFound (when provided name is invalid)
  • tasks (callback=None)

    A list of tasks currently active on the server.

  • users ‹property›

    The _users system database.

    Returns

    • Database. This property is a synonym for self.db('_users')
  • uuids (count=1, callback=None)

    Retrieve a batch of uuids

    Args

    • count (int): optional number of uuids to retrieve

    Returns

    • list. A list of uuid strings of length=count
  • version (callback=None)

    The version string of the CouchDB server.

corduroy.
Database

Represents a single DB on a couch server.

This is the primary class for interacting with documents, views, changes, et al.

  • __init__ (name, auth=None)

    Initialize the database object.

    Args

    • name (str): either a full url path to the database, or just a database name (to which the host specified in corduroy.defaults will be prepended)
    • auth (tuple): optional login information. e.g., ('username', 'password')
  • changes (callback=None, **opts)

    Retrieve a list of changes from the database or begin listening to a continuous feed.

    Kwargs

    • since (int): the earliest seq value that should be reported
    • limit (int): maximum number of changes to return
    • filter (str): name of a filter function (e.g., myddoc/subset)
    • include_docs (bool): if true, each element of the 'results' array in the return value will also containt a 'doc' attribute
    • feed (str): if 'continuous', a ChangesFeed object will be created and begin listening to the specified _changes feed.
    • callback (function w/ signature ƒ(seq, changes)): the callback will be invoked repeatedly whenever new changes arrive. The seq argument is the integer value of the most recent seq in that batch. the changes argument is a list of dicts of the form: [{seq:0, id:'', changes:[]}, …]
    • latency (default=1): minimum time period between invocations of the callback. When set to 0, the callback will be invoked for every individual change. With higher values, changes will be batched for efficiency's sake.
    • heartbeat (int): time period between keepalive events (in seconds).
    • timeout (int): maximum period of inactivity (in seconds) before which the server will send a response.

    Returns

    • When called without requesting a feed: a dictionary of the form {last_seq:0, results:[{id:'', seq:0, …}, …]}
    • If called with feed='continuous' and a valid callback: a ChangesFeed object
  • cleanup (callback=None)

    Clean up old design document indexes.

    Returns

    • dict of the form {ok:True}
  • commit (callback=None)

    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, callback=None)

    Compact the database or a design document's index.

    Args

    • ddoc (str): optional design doc name
  • copy (source, dest, callback=None)

    Copy a given document to create a new document or overwrite an old one.

    Args

    • source (str, dict): either a string containing an ID or a dict with _id and _rev keys specifying the document to be copied
    • dest (str, dict): either a string containing an ID or a dict with _id and _rev keys specifying the document to be created/overwritten

    Returns

    • dict of form {id:'', rev:''} identifying the destination document.

    Raises

    • Conflict (when dest doc already exists and an up-to-date _rev was not specified)
  • delete (doc, callback=None)

    Delete the given document from the database.

    Args

    • doc (dict-like): an object with _id and _rev keys identifying the doc to be deleted

    Returns

    • dict: {ok:True, id:'', rev:''}

    Raises

    • NotFound (when doc['_id'] does not exist) Conflict (when dest doc already exists and an up-to-date _rev was not specified)
  • delete_attachment (doc, filename, callback=None)

    Delete the specified attachment.

    Args

    • doc (dict-like): an object with _id and _rev keys
    • filename (str): the name of the attachment to be deleted in the given doc

    Side Effects

    • Will update the doc argument's _rev value upon succesfully deleting the attachment

    Returns

    • dict {ok:True}

    Raises

    • NotFound, Conflict.
  • exists (callback=None)

    Check whether this Database object corresponds to an existing db on the server

    Returns

    • boolean
  • get (id_or_ids=False, callback=None, **options)

    Return the document(s) with the specified ID(s).

    Args

    • id_or_ids (str, list): either a single ID or a list of IDs to fetch in a bulk request

    Kwargs

    • rev (str): if present, specifies a specific revision to retrieve
    • revs (bool): if true, add a _revs attribute to the returned doc
    • revs_info (bool): if true, add a _revs_info attribute to the returned doc
    • When called with a list of IDs, all standard view options can be applied (see Database.view for a complete listing).

    Returns

    • If a single ID is requested, returns a corresponding Document or raises an exception if the doc does not exist.
    • If a list of IDs was requested, returns a corresponding list of Document objects. Requesting IDs referencing non-existent docs will not raise an exception but will place a corresponding None in the list of returned docs.

    Raises

    • NotFound (when a single ID is requested and no corresponding doc is found)
  • get_attachment (id_or_doc, filename, callback=None)

    Return an attachment from the specified doc and filename.

    Args

    • doc (str, dict-like): an ID string or dict with an _id key
    • filename (str): the name of the attachment to retrieve

    Returns

    • str. The raw attachment data as a bytestring
  • info (ddoc=None, callback=None)

    Fetch information about the database or a design document.

    Args

    • ddoc (str): optional design doc name

    Returns

    • dict. Equivalent to a GET on the database or ddoc's url

    Raises

    • NotFound
  • list (name, view, callback=None, **options)

    Format a view using a 'list' function.

    Args

    • name (str): the ddoc and list function name (e.g., myddoc/weekly) view (str): a view to run the list against. if the view is in the same ddoc as the list function, just its name can be passed (e.g., 'stats' instead of 'myddoc/stats'). Otherwise the ddoc should be included in the view name.

    Returns

    • object with two attributes of interest: * headers: a dictionary of the response headers * body: either a bytestring or a decoded json object (if the response content type was application/json)
  • pull (source, callback=None, **options)

    Initiate a replication from a source url to this database

    Args

    • source (str, Database): the database from which to replicate
    • Kwargs (c.f., Couch.replicate): _id (str): an optional replication_id. If provided, a doc will be created in the _replicator database for subsequent querying. If not provided, the legacy _replicate API will be used instead.
    • cancel (bool): if true, cancel the replication
    • continuous (bool): if True, set the replication to be continuous
    • create_target (bool): if True, creates the target database
    • doc_ids (list): optional list of document IDs to be synchronized
    • proxy (str): optional address of a proxy server to use
  • purge (docs, callback=None)

    Perform purging (complete removal) of the given documents.

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

    Think thrice before doing this.

    Args

    • docs (list): containing dicts of the form {_id:'', _rev:''}

    Returns

    • dict of the form {purge_seq:0, purged:{id1:[], id2:[], ...}}
  • push (target, callback=None, **options)

    Initiate a replication from this database to a target url

    Args

    • target (str, Database): the target database
    • Kwargs (c.f., Couch.replicate): _id (str): an optional replication_id. If provided, a doc will be created in the _replicator database for subsequent querying. If not provided, the legacy _replicate API will be used instead.
    • cancel (bool): if true, cancel the replication
    • continuous (bool): if True, set the replication to be continuous
    • create_target (bool): if True, creates the target database
    • doc_ids (list): optional list of document IDs to be synchronized
    • proxy (str): optional address of a proxy server to use
  • put_attachment (doc, content, filename=None, content_type=None, callback=None)

    Create or replace an attachment.

    Args

    • doc (dict-like): an object with _id and _rev keys
    • content (str, file): the attachment data
    • filename (str): optionally specify the name to use (unnecessary w/ file objects)
    • content_type (str): optionally specify the mime type to use (unnecessary w/ file objects)

    Side Effects

    • Will update the doc argument's _rev value upon succesfully updating the attachment

    Returns

    • dict of form {ok:True, id:'', rev:''}

    Raises

    • NotFound, Conflict
  • query (map_src, reduce_src=None, callback=None, **options)

    Create a temporary view using the provided javascript function(s) and perform a mind-bendingly inefficient ad-hoc query.

    Args

    • map_src (str): a map function string such as: 'function(doc){emit(null,null)}'
    • reduce_src (str): optionally include a reduce function string: 'function(key, values, rereduce){return sum(values)}' or the name of a builtin (_sum, _count, or _stats)

    Kwargs

    • all standard view options (see Database.view)

    Returns

    • View. An iterable list of Row object.
  • revisions (id, callback=None, **options)

    Return all available revisions of the given document.

    Args

    • id (str): ID of the doc whose revisions to fetch

    Returns

    • list. All prior _rev strings sorted reverse chronologically

    Raises

    • NotFound.
  • save (doc_or_docs=None, merge=None, force=False, callback=None, **options)

    Create a new document or update an existing document.

    Args

    • doc_or_docs (dict, list): either a single dict-like object or a list of many

    Kwargs

    • batch (str): if equal to "ok" when submitting a single document, the server will defer writing to disk (speeding throughput but risking data loss)
    • all_or_nothing (boolean): if True when submitting a list of documents, conflict checking will be disabled and either the entire list of docs will be written to the database or none will (see couchdb docs for more details on the not- entirely-intuitive semantics).
    • force (bool): if True, will retry any writes that caused a conflict after fetching the current _revs from the server. This will not necessarily succeed if the database is write-heavy due to the race condition between retrieving the _rev and attempting the update. The use of force outside of a debugging context is highly discouraged.
    • merge (function w/ signature ƒ(local_doc, server_doc)): If the inital update request causes any conflicts, the current server copy of each conflicting doc will be fetched and the merge function will be called for each local/remote pair. The merge function should return either a dict-like object to be written to the database or (in case the write attempt should be abandoned) None.

    Side Effects

    • All docs passed as arguments will have their _id and/or _rev updated to reflect a successful write. In addition, these up-to-date dicts can be found in the return value's .resolved property (useful in an async context where the callback function doesn't have the original arguments in its scope)

    Returns

    • ConflictResolution. An object with two attributes of interest: * pending: a dictionary (keyed by _id) of docs which were not successfully written due to conflicts * resolved: a dictionary (keyed by _id) of docs which were successfully written

    Raises

    • Conflict.
    • As with the Database.get method, exceptions will be raised in the single-doc case, but when dealing with a list of docs, errors will be signaled on a doc-by-doc basis in the return value.
  • security (value=None, callback=None)

    Access the database's _security object

    If called without arguments, returns the security object. If called with a dict, sets the security object to that value.

    Args

    • value (dict): the new security object to be saved to the database

    Returns

    • dict. The current security object.
  • show (name, id=None, callback=None, **options)

    Call a 'show' function.

    Args

    • name (str): the show function to use (e.g., myddoc/atomfeed)
    • id (str): optional ID of the doc on which the show function will be run

    Returns

    • object with two attributes of interest: * headers: a dictionary of the response headers * body: either a bytestring or a decoded json object (if the response content type was application/json)
  • update (name, id=None, body=None, callback=None, **options)

    Calls a server side update handler.

    Args

    • name (str): the update-handler function name (e.g., myddoc/in_place_update)
    • id (str): optionally specify the ID of a doc to update

    Kwargs

    • body (str, dict): optionally include data in the POST body. Dicts will be form-encoded and will appear in your update handler in the req.form field. Strings will be passed as-is and can be found in req.body.
    • Other kwargs will be urlencoded and appended to the query string.
  • view (name, callback=None, **options)

    Query a view.

    All of the query args in the HTTP api can be passed as keyword args. Key values should be json-serializeable objects (abbreviated as obj below) of the form defined in your view function.

    Args

    • name (str): a view name of the form 'myddoc/viewname'

    Kwargs

    • key (obj): retrieve only rows matching this key
    • keys (list): a list of key values to retrieve
    • descending (bool): whether to invert the ordering of the rows. This ordering is applied before any key filtering takes place, thus you may need to reverse your starts and ends when toggling this.
    • startkey (obj): key of the first row to include in the results
    • endkey (obj): key of the final row of results
    • inclusive_end (bool): by default, include rows matching endkey in the results. If False, treat endkey as defining the first rows to be *excluded* from the results.
    • startkey_docid (str): within the rows bounded by startkey and endkey, perform a further filtering by discarding rows before this ID.
    • endkey_docid (str): discard rows between this doc ID and endkey
    • include_docs (bool): if True, each Row in the results will have the corresponding document in its .doc attr.
    • limit (int): the maximum number of rows to retrieve
    • stale (str): specify how to handle view indexing, * 'ok': build results from the current index even if it's out of date * 'update_after': return stale results but trigger a view re-index for the benefit of subsequent queries.
    • skip (int): of the rows that would be returned on the basis of any prior key filtering, discard this many from the beginning.
    • update_seq (bool): include an update_seq field in the response indicating the seq of the most recent indexing (from which the results were pulled).
    • reduce (bool): if False, ignore the reduce function on this view and return the output of its map step.
    • group (bool): if True, generate a row for each distinct key in the reduce results. By defualt, the reduce function's output will boil down to a single row.
    • group_level (int or 'exact'): when using ‘complex keys’ (i.e., lists) group_level defines how many elements from each key should be used when deciding if rows have ‘distinct’ keys for the purposes of the reduction step.

    Returns

    • View.

corduroy.
View

Iterable representation of a set of results from a view query

Attributes

  • options (dict): the query arguments that generated these results
  • total_rows (int): the number of rows that matched the query (may be larger than len(view) if a limit is in the options dict)
  • offset (int): the number of rows preceding this set of results
  • rows (list): a list of Row objects (as are returned when iterating over the view object itself).

corduroy.
Row

Representation of a single row of results from a view query

  • doc ‹property›

    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 ‹property›

    Couch's description of an error if one occurred, otherwise None

  • id ‹property›

    The ID of the doc that emitted this row if it exists or None if it doesn't (e.g., when querying a view with a reduce function).

  • key ‹property›

    The emitted key

  • value ‹property›

    The emitted value

corduroy.
Document

A dictionary subclass with couch-friendly additions.

Inherits from odict to preserve key-ordering when converting to/from json and from adict to allow for dot-syntax access to dictionary items.

corduroy.
Status

Contains the server response from an HTTP request.

Status objects are returned as the final argument to callback functions when returning from an asynchronous database request.

Attributes

  • ok (bool): True if the server gave a non-error response code
  • code (int): the HTTP response code
  • headers (dict): the response headers
  • exception (HTTPError): None if the request was successful, or an HTTPError subclass
  • error (cls): the class of the exception (or None). This is redundant but allows for the syntax if status.error is NotFound in callback functions.

corduroy.
ChangesFeed

Persistent listener to a Database's _changes endpoint

Attributes

  • callback (function w/ signature ƒ(seq, changes)): the user callback to which incoming changesets will be passed.
  • latency (float): the minimum time (in seconds) between invocations of the user callback.

corduroy.
ConflictResolution

The result of an attempt to write to the database.

Presents the results of a Database.save call and provides syntax for resolution of any conflicted documents

Attributes

  • pending (dict): A dictionary (keyed by _id) of docs that were not successfully written due to conflicts. e.g., {some_doc: {doc:{_id:"some_doc", …}, error:"conflict"}, …}
  • resolved (dict): A dictionary (keyed by _id) of docs that were written without error. Their _id and _rev keys have been updated to reflect the save.
  • overwrite (callback=None)

    Attempt to replace the server's copy of the docs with those in .pending

    This is a brute-force method of resolving conflicts. The database is queried for the _revs of all the docs with pending conflicts. The local copies of the docs are then updated with the up-to-date _revs and a bulk-save is attempted.

    Returns

    • self (after updating the pending and resolved dicts)
  • resolve (merge, callback=None)

    Attempt to merge the local and server versions of docs with pending conflicts.

    Allows a user-provided function to decide how to resolve each conflict and what (if anything) ought to be written to the server.

    Args

    • merge (function w/ signature ƒ(local_doc, server_doc)): This function should create a new version of the doc incorporating the proper elements of both copies. If a dict-like object is returned, an attempt will be made to write it to the database. If None is returned, the document will be skipped in the write attempt and remains ‘pending’.

    Returns

    • self (after updating the pending and resolved dicts)

corduroy.
@relax

A decorator for simplifying async couchdb access from Tornado.

Methods using this decorator will be able to make asynchronous calls to the database without needing to provide explicit callbacks (and restoring traditional exception handling in the process). It decides between applying tornado's @asynchronous and @gen.engine decorators as appropriate for a given method.

Its primary function is to intercept yield statements in your request handler and to evaluate them asynchronously (with an automatic callback that it inserts). When the database request completes, the callback will resume your function at the yield point and pass the received data off with a simple assignment.

Exceptions

Everything that can go wrong…

Couch gives quite a bit of feedback through numeric HTTP error codes. These exceptions give less-unweildy names to some of the more common ones:

HTTPError

  • Base class for all exceptions with HTTP status codes >= 400.

NotFound

  • Raised when a 404 error occurs.

Conflict

  • Raised when a 409 error occurs.

PreconditionFailed

  • Raised when a 412 error occurs.

ServerError

  • Raised when an HTTP status code >=500 occurs.