Skip to main content

CouchDB v2.x Python 3 interface in a single module. Also a command line tool.

Project description


CouchDB v2.x Python 3 interface in a single module. Also a command line tool; see below.

Most, but not all, features of this module work with CouchDB version < 2.0.


The CouchDB2 module is available at PyPi. It can be installed using pip:

$ pip install couchdb2

The module relies on requests:


  • 1.9.3
  • 1.9.2
  • 1.9.1
  • 1.9.0
    • Changed put_attachment and delete_attachment to update the input doc by the new _rev value.
  • 1.8.5
    • Added ids(): Return an iterator over all document identifiers.
  • 1.8.4
    • Added get_bulk(ids): Get several documents in one operation.

Example code

import couchdb2

server = couchdb2.Server()   # Arguments required according to local setup
db = server.create('test')

doc1 = {'_id': 'myid', 'name': 'mydoc', 'level': 4}
doc = db['myid']
assert doc == doc1

doc2 = {'name': 'another', 'level': 0}
# {'_id': '66b5...', '_rev': '1-f3ac...', 'name': 'another', 'level': 0}

               {"name": {"map": "function (doc) {emit(, null);}"}
result = db.view('mydesign', 'name', key='another', include_docs=True)
assert len(result) == 1
print(result[0].doc)         # Same printout as above, using OrderedDict



server = Server(href='http://localhost:5984/', username=None, password=None,
                use_session=True, ca_file=None)

Connection to the CouchDB server.

If use_session is true, then an authenticated session is used transparently. Otherwise, username and password is sent with each request.

ca_file can point to a file or a directory containing CAs if you need to access databases in HTTPS.



Property attribute providing the version of the CouchDB server software.



Property attribute providing the user context of the connection.



Return a simple string representation of the server interface.



Return the number of user-defined databases.


for db in server: ...

Return an iterator over all user-defined databases on the server.


db = server[name]

Get the named database.


if name in server: ...

Does the named database exist?


data = server()

Return meta information about the server.


if server.up(): ...

Is the server up and running, ready to respond to requests?

CouchDB version >= 2.0.


db = server.get(name, check=True)

Get the named database. If check is true, then raise NotFoundError if the the database does not exist.


db = server.create(name)

Create the named database.


data = server.get_config(nodename='_local')

Get the named node's configuration.


data = server.get_active_tasks()

Return a list of running tasks.


data = server.get_cluster_setup(config)

Return the status of the node or cluster.

CouchDB version >= 2.0.



Configure a node as a single node, as part of a cluster, or finalize a cluster.

CouchDB version >= 2.0.


data = server.get_membership()

Return data about the nodes that are part of the cluster.

CouchDB version >= 2.0.


data = server.set_replicate(doc)

Request, configure, or stop, a replication operation.


data = server.get_scheduler_jobs(limit=None, skip=None)

Get a list of replication jobs.

CouchDB version >= 2.0.


data = server.get_scheduler_docs(limit=None, skip=None,
                                 replicator_db=None, docid=None)

Get information about replication document(s).

CouchDB version >= 2.0.


data = server.get_node_stats(nodename='_local')

Return statistics for the running server.

CouchDB version >= 2.0.


data = server.get_node_system(nodename='_local')

Return various system-level statistics for the running server.

CouchDB version >= 2.0.


db = Database(server, name, check=True)

Interface to a named CouchDB database.

If check is true, then raise NotFoundError if the the database does not exist.



Return the name of the CouchDB database.



Return the number of documents in the database.


if id in db: ...

Does a document with the given id exist in the database?


for doc in db: ...

Return an iterator over all documents in the database.


doc = db[id]

Return the document with the given id.


if db.exists(): ...

Does the database exist?



Raises NotFoundError if the database does not exist.



Create the database.



Delete the database and all its contents.


data = db.get_info()

Return a dictionary with information about the database.


data = db.get_security()

Return a dictionary with security information for the database.



Set the security information for the database.


db.compact(finish=False, callback=None)

Compact the CouchDB database by rewriting the disk database file and removing old revisions of documents.

If finish is True, then return only when compaction is done. In addition, if defined, the function callback(seconds) is called every second until compaction is done.



Compact the view indexes associated with the named design document.



Remove unnecessary view index files due to changed views in design documents of the database.


doc = db.get(id, rev=None, revs_info=False, default=None, conflicts=False)

Return the document with the given id, or the default value if not found.

If conflicts is True, includes information about conflicts in document (in _conflicts attribute).


doc = db.get_bulk(ids)

Get several documents in one operation, given a list of document ids, each of which is a string (the document id), or a tuple of the document id and revision.

Returns a list of documents. If no document is found for a specified id or (id, rev), None is returned in that slot of the list.


for id in db.ids(): ...

Return an iterator over all document identifiers.



Insert or update the document.

If the document is already in the database, the _rev item must be present in the document; its value will be updated.

If the document does not contain an item _id, one will be added having a UUID4 value. The _rev item will also be added.



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

The return value of this method is a list containing a tuple for every element in the docs 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.

docs : 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 (list) over the resulting documents.



Delete the document.



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.


data = db.get_designs()

Return the design documents for the database.

CouchDB version >= 2.2.


data = db.get_design(designname)

Get the named design document.


db.put_design(designname, doc, rebuild=True)

Insert or update the design document under the given name.

If the existing design document is identical, no action is taken and False is returned, else the document is updated and True is returned.

If rebuild is True, force view indexes to be rebuilt after update. This may take some time.

Example of doc:

      {"map": "function (doc) {emit(, null);}"},
      {"map": "function (doc) {emit(, 1);}",
       "reduce": "_sum"},
      {"map": "function (doc) {emit(, null);}",
       "reduce": "_count"}

More info:


result = db.view(designname, viewname, key=None, keys=None,
                 startkey=None, endkey=None, skip=None, limit=None,
                 sorted=True, descending=False,
                 group=False, group_level=None, reduce=None,

Return a ViewResult object, containing Row objects in the attribute rows (a list).

If include_docs is True, then reduce is forced to False.


data = db.get_indexes()

Return a list of all indexes in the database.

CouchDB version >= 2.0.


db.put_index(fields, ddoc=None, name=None, selector=None)

Store a Mango index specification. CouchDB v2.x only.

  • fields is a list of fields to index.
  • ddoc is the design document name. Generated if none given.
  • name is the name of the index. Generated if none given.
  • selector is a partial filter selector, which may be omitted.

Returns a dictionary with items id (design document name; sic!), name (index name) and result (created or exists).

CouchDB version >= 2.0.


data = db.find(selector, use_index=None, limit=None, skip=None, sort=None,
               fields=None, bookmark=None, update=None, conflicts=None)

Select documents according to the Mango index selector.

Returns a dictionary with items docs, warning, execution_stats and bookmark.

If conflicts is True, includes information about conflicts in documents (in _conflicts attribute).

CouchDB version >= 2.0.


data = db.explain(selector, use_index=None, limit=None, skip=None, sort=None,
                  fields=None, bookmark=None, update=None)

Return info on which index is being used by the query.

CouchDB version >= 2.0.


fileobj = db.get_attachment(doc, filename)

Return a file-like object containing the content of the attachment.


rev = db.put_attachment(doc, content, filename=None, content_type=None)

content is a string or a file-like object. Return the new revision of the document.

Note: Since version 1.9.0, the _rev item in the input doc is updated.

If filename is not provided, then an attempt is made to get it from the content object.


rev = db.delete_attachment(doc, filename)

Delete the attachment. Return the new revision of the document.

Note: Since version 1.9.0, the _rev item in the input doc is updated.


(ndocs, nfiles) = db.dump(filepath, callback=None)

Dump the entire database to a tar file.

If defined, the function callback(ndocs, nfiles) is called every 100 documents.

If the filepath ends with .gz, then the tar file is gzip compressed. The _rev item of each document is kept.

A tuple (ndocs, nfiles) is returned.


(ndocs, nfiles) = db.undump(filepath, callback=None)

Load the tar file, which must have been produced by dump.

If defined, the function callback(ndocs, nfiles) is called every 100 documents.

NOTE: The documents are just added to the database, ignoring any _rev items.

A tuple (ndocs, nfiles) is returned.



Base CouchDB2 exception.



No such entity exists.



Invalid request; bad name, body or headers.



Could not create the entity; it exists already.



Wrong or missing _rev item in the document to save.



Current user not authorized to perform the operation.



Bad Content-Type value in the request.



Internal server error.


Object returned as result from db.view().

ViewResult(rows, offset, total_rows)


  • rows: the list of Row objects.
  • offset: the offset used for the set of rows.
  • total_rows: the total number of rows selected.



Return the number of rows in the view result.


for row in viewresult: ...

Return an iterator over all rows in the view result.


row = viewresult[i]

Return the indexed view result row.


data = viewresult.json()

Return view result data in a JSON-like representation.


Named-tuple object returned in ViewResult list attribute rows.

Row(id, key, value, doc)
  • id: the identifier of the document, if any.
  • key: the key for the index row.
  • value: the value for the index row.
  • doc: the document, if any.


Alias for field number 0


Alias for field number 1


Alias for field number 2


Alias for field number 3

Utility functions


read_settings(filepath, settings=None)

Read the settings lookup from a JSON format file. If settings is given, then return an updated copy of it, else copy the default settings, update, and return.

Command line tool

The module is also a command line tool for interacting with the CouchDB server. Installing it using pip will set up the command couchdb2.

Settings for the command line tool are updated from the following sources, in the order given and if existing:

  1. Default values are
      "SERVER": "http://localhost:5984",
      "DATABASE": null,
      "USERNAME": null,
      "PASSWORD": null
  2. Read from the JSON file ~/.couchdb2 (in your home directory).
  3. Read from the JSON file settings.json (in the current working directory).
  4. Read from the JSON file given by command line option --settings FILEPATH.


To print available command options:

$ couchdb2 -h
usage: couchdb2 [options]

CouchDB v2.x command line tool, leveraging Python module CouchDB2.

optional arguments:
  -h, --help            show this help message and exit
  --settings FILEPATH   settings file in JSON format
  -S SERVER, --server SERVER
                        CouchDB server URL, including port number
  -d DATABASE, --database DATABASE
                        database to operate on
  -u USERNAME, --username USERNAME
                        CouchDB user account name
  -p PASSWORD, --password PASSWORD
                        CouchDB user account password
  -q, --password_question
                        ask for the password by interactive input
                        file or directory containing CAs
  -o FILEPATH, --output FILEPATH
                        write output to the given file (JSON format)
  --indent INT          indentation level for JSON format output file
  -y, --yes             do not ask for confirmation (delete, destroy)
  -v, --verbose         print more information
  -s, --silent          print no information

server operations:
  -V, --version         output CouchDB server version
  --list                output a list of the databases on the server

database operations:
  --create              create the database
  --destroy             delete the database and all its contents
  --compact             compact the database; may take some time
  --compact_design DDOC
                        compact the view indexes for the named design doc
  --view_cleanup        remove view index files no longer required
  --info                output information about the database
  --security            output security information for the database
  --set_security FILEPATH
                        set security information for the database from the
                        JSON file
  --list_designs        list design documents for the database
  --design DDOC         output the named design document
  --put_design DDOC FILEPATH
                        store the named design document from the file
  --delete_design DDOC  delete the named design document
  --dump FILEPATH       create a dump file of the database
  --undump FILEPATH     load a dump file into the database

document operations:
  -G DOCID, --get DOCID
                        output the document with the given identifier
                        store the document; arg is literal doc or filepath
  --delete DOCID        delete the document with the given identifier

attachments to document:
                        attach the specified file to the given document
                        remove the attached file from the given document
  --get_attach DOCID FILENAME
                        get the attached file from the given document; write
                        to same filepath or that given by '-o'

query a design view, returning rows:
  --view SPEC           design view '{design}/{view}' to query
  --key KEY             key value selecting view rows
  --startkey KEY        start key value selecting range of view rows
  --endkey KEY          end key value selecting range of view rows
  --startkey_docid DOCID
                        return rows starting with the specified document
  --endkey_docid DOCID  stop returning rows when specified document reached
  --group               group the results using the 'reduce' function
  --group_level INT     specify the group level to use
  --noreduce            do not use the 'reduce' function of the view
  --limit INT           limit the number of returned rows
  --skip INT            skip this number of rows before returning result
  --descending          sort rows in descending order (swap start/end keys!)
  --include_docs        include documents in result

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for CouchDB2, version 1.9.3
Filename, size File type Python version Upload date Hashes
Filename, size CouchDB2-1.9.3-py3-none-any.whl (20.3 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size CouchDB2-1.9.3.tar.gz (23.7 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page