couchpy.client – CouchDB client

Client implements the client interface for a CouchDB server. Aside from this, Client instance provide pythonified way of accessing the database systems, for example, a Client instance behave like a dictionary of databases. A Client constructor typically takes httpurl (for server) as its argument. If url is not provided, ENVIRONMENT variable COUCHDB_URL will be used if available, if that is also not available then the default url ‘http://localhost:5984/‘ will be assumed.

A collection of examples using Client objects.

Create a client object,

>>> couch = Client()

Check for server availability,

>>> bool( couch )
True

To get server information,

>>> couch()
{ "couchdb" : "Welcome", "version" : "<version>" }

Get list of all available database names,

>>> couch.all_dbs()
[ <Database u'sessions'>, <Database u'bootdb'>, <Database u'_users'> ]

Or, iterate over all databases in the server, obtaining a list of couchpy.database.Database objects,

>>> [ db for db in couch ]
[ <Database u'sessions'>, <Database u'bootdb'>, <Database u'_users'> ]

Number of databases present in the server,

>>> len(couch)
3

Get or Delete a database (python style).

>>> couch['bootdb']
<Database u'bootdb'>
>>> del couch['bootdb']

Check whether a database is present,

>>> couch.has_database( '_users' )
True
>>> '_users' in couch               # Python way
True
>>> 'contacts' in couch
False

Get server statistics,

>>> couch.stats()
{ ... }     # A dictionary of server statistics

Get a list of 2 univerally unique IDs, the count argument is optional.

>>> c.uuids( 2 )
[ u'a0cf4956301a349a0ecc99370e74331e', u'93e4ec906703b7a00abbfd46b46425fb' ]

Operations that require admin privileges :

Restart couchdb server instance,

>>> couch.restart()

Get server log (required admin privileges)

>>> logs = couch.log().splitlines()
>>> couch.log( offset=100, bytes=10 )

Server configuration

>>> couch.config()      # Get the current configuration dictionary, section wise
>>> couch.config( section='uuids' )
{u'algorithm': u'utc_random'}
>>> couch.config( section='uuids', key='algorithm' )
u'utc_random'
>>> couch.config( section='uuids', key='algorithm', value='random') # Update
>>> couch.config( section='uuids', key='algorithm' )                
u'random'
>>> couch.config( section='uuids', key='algorithm', delete=True )   # Delete
>>> couch.addadmin( 'sokochi', 'joe123' ) # Add a server admin (username,passwd)
>>> couch.deladmin( 'sokochi' )           # Delete a server admin
>>> couch.admins()                        # List of server admins
{ 'pratap' : u'-hashed-cf8f18ed9a17e6d6....' }

Server authetication and session,

>>> couch.login( username, password )
>>> couch.authsession() # Authenticated user's session information
>>> couch.logout()      # Authenticated user will be identified via cookie.

Database operations :

>>> c.put('blog')                       # Create database
<Databse 'blog'>
>>> c.Database('blog')                  # Get the Database instance
<Databse 'blog'>
>>> c.delete( 'blog' )                  # Delete database
>>> c.has_database( 'blog' )            # Check whether database is present
True

Miscellaneous operation,

>>> couch.version()
u'1.0.1'
>>> couch.ispresent()
True

Module Contents

class couchpy.client.Client(url=None, config=None, hthdrs=None, cookie=None)

Client interface for CouchDB server.

url,
Server http url.
config,
Configuration parameters.
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.
cookie
cookie value for authenticated sessions. Value can be of type basestring or cookie.SimpleCookie object.
__contains__(name)

Return True if database name is present, else False. Refer Client.has_database()

__iter__()

Iterate over all database available in the server. Each iteration yields couchpy.database.Database instance corresponding to a database in the server. Refer Client.all_dbs()

__len__()

Return the count of database available in the server.

__nonzero__()

If returns True, then the server is available. This is essentially a one time check to know whether the database instance pointed by server-url is available. Subsequent checks will simply return the remembered status. To make a fresh request for server availability use, Client.ispresent() method.

__delitem__(name)

Remove database name from server. Refer Client.delete() method.

__getitem__(name)

Return a couchpy.database.Database instance for database, name. Refer Client.Database() method

__call__()

Check whether CouchDB instance is alive and return the welcome string, which will be something like

>>> c = Client()
>>> c()
{ "couchdb" : "Welcome", "version" : "<version>" }

To just check for server availability, use Client.ispresent() method.

version()

Version string from CouchDB server.

ispresent()

Do a fresh check for server availability. This will emit a HEAD request to the server. For efficiency reasons you can just use the boolean operator on the Client instance like,

>>> bool( couch )
active_tasks(hthdrs={})

Obtain a list of active tasks. The result is a JSON converted array of the currently running tasks, with each task being described with a single object.

>>> couch.active_tasks()
[ {
  "pid"    : "<0.11599.0>",  # Erlang pid
  "status" : "Copied 0 of 18369 changes (0%)",
  "task"   : "recipes",
  "type"   : "Database Compaction"
  },
  ....
]

Admin-Prev, Yes

all_dbs(hthdrs={})

Return a list of all the databases as couchpy.database.Database objects from the CouchDB server.

Admin-Prev, No

log(bytes=None, offset=None, hthdrs={})

Get CouchDB log, equivalent to accessing the local log file of the corresponding CouchDB instance. When you request the log, the response is returned as plain (UTF-8) text, with an HTTP Content-type header as text/plain. Returns a stream of text bytes.

bytes,
Bytes to be returned.
offset,
Offset in bytes where the log tail should be started.

Admin-Prev, Yes

restart(hthdrs={})

Restart CouchDB server instance. You must be authenticated as admin user with administrative privileges for this to work. Returns a Boolean, indicating success or failure

Admin-Prev, Yes

stats(*paths, **kwargs)

Return a JSON converted object containing statistics from CouchDB server. The object is structured with top-level sections collating statistics for a range of entries, with each individual statistic being easily identified, and the content of each statistic is self-describing. You can also access individual statistics by passing statistics-section and statistic-id as positional arguments, similiar to the following example

>>> c.stats( 'couchdb', 'request_time' )
{'couchdb': {'request_time': {'current': 1265.6880000000001,
                              'description': 'length of a request inside CouchDB without MochiWeb',
                              'max': 235.0,
                              'mean': 14.717000000000001,
                              'min': 3.0,
                              'stddev': 29.754999999999999,
                              'sum': 1265.6880000000001} } }

Admin-Prev, No

uuids(count=None, hthdrs={})

Return count number of uuids, generated by the server. These uuid can be used to compose document ids. Refer to CouchDB API manual to know more about UUIDs.

config(section=None, key=None, hthdrs={}, **kwargs)

Configuration of CouchDB server. If section and key is not specified, returns the entire CouchDB server configuration as a JSON converted structure. The structure is organized by different configuration sections.

If section parameter is passed, returns the configuration structure for a single section specified by section.

If section and key is specified, returns a single configuration value from within a specific configuration section.

To update a particular section/key, provide a keyword argument called value. Value will be converted to JSON string and passed on to the server.

To delete a particular section/key supply delete=True keyword argument.

Returns nested dictionary of configuration name and value pairs, organized by section.

Admin-Prev, Yes

addadmin(name, password)

Create a server admin by name name with password.

Admin-Prev, Yes

deladmin(name)

Delete server admin user name

Admin-Prev, Yes

admins()

List of admin user

Admin-Prev, Yes

login(username, password, hthdrs={})

Login with username and password. Uses session-cookie for authentication. Cookie is remembered on this client’s instance and will be used for all subsequent request to CouchDB server, until a Client.logout() method. is called.

Returns a tuple of (status, header, payload) from HTTP response, header contains the cookie information if the login was successful,

logout(hthdrs={})

Logout from authenticated DB session. The authentication cookie is no longer valid.

authsession(hthdrs={})

Fetch the authenticated session information for this client. At any point only one user can remain authenticated for a single client instance. Note that browser-session is not handled by the client.

put(name, hthdrs={})

Create a new database with the given name. Return, a couchpy.database.Database object representing the created database.

Admin-Prev, Yes

delete(db, hthdrs={})

Delete database db, which can be passed as an instance of couchpy.database.Database class or as database-name.

Admin-Prev, Yes

has_database(name, hthdrs={})

Return a boolean, indicating whether database name is available on the server.

Admin-Prev, No

Database(name, *args, **kwargs)

Convenience method to access the Database class under the context of this client instance. Return a couchpy.database.Database object representing the database name.

Admin-Prev, No

commit()

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

Call to this method will bulk commit all the active documents (dirtied) under every open database for this client.

replicate(source, target, hthdrs={}, **options)

– TBD –

Request, configure, or stop, a replication operation.

source
URL of the source database
target
URL of the target database

key-word arguments,

cancel,
Cancels the replication
continuous,
Boolean to configure the replication to be continuous
create_target,
Creates the target database
doc_ids,
Array of document IDs to be synchronized
proxy,
Address of a proxy server through which replication should occur

CouchPy

Table Of Contents

Previous topic

Introduction

Next topic

couchpy.database – CouchDB database interface

This Page