client

Top level API module that maps to a Cloudant or CouchDB client connection instance.

class cloudant.client.Cloudant(cloudant_user, auth_token, **kwargs)

Bases: cloudant.client.CouchDB

Encapsulates a Cloudant client, handling top level user API calls having to do with session and database management.

Maintains a requests.Session for working with the instance specified in the constructor.

Parameters can be passed in to control behavior:

Parameters:
  • cloudant_user (str) – Username used to connect to Cloudant.
  • auth_token (str) – Authentication token used to connect to Cloudant.
  • account (str) – The Cloudant account name. If the account parameter is present, it will be used to construct the Cloudant service URL.
  • url (str) – If the account is not present and the url parameter is present then it will be used to set the Cloudant service URL. The url must be a fully qualified http/https URL.
  • x_cloudant_user (str) – Override the X-Cloudant-User setting used to authenticate. This is needed to authenticate on one’s behalf, eg with an admin account. This parameter must be accompanied by the url parameter. If the url parameter is omitted then the x_cloudant_user parameter setting is ignored.
  • encoder (str) – Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder.
  • adapter (requests.HTTPAdapter) – Optional adapter to use for configuring requests.
bill(year=None, month=None)

Retrieves Cloudant billing data, optionally for a given year and month.

Parameters:
  • year (int) – Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by month.
  • month (int) – Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by year.
Returns:

Billing data in JSON format

classmethod bluemix(vcap_services, instance_name=None, service_name=None, **kwargs)

Create a Cloudant session using a VCAP_SERVICES environment variable.

Parameters:
  • vcap_services (dict or str) – VCAP_SERVICES environment variable
  • instance_name (str) – Optional Bluemix instance name. Only required if multiple Cloudant instances are available.
  • service_name (str) – Optional Bluemix service name.

Example usage:

import os
from cloudant.client import Cloudant

client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'),
                          'Cloudant NoSQL DB')

print client.all_dbs()
cors_configuration()

Retrieves the current CORS configuration.

Returns:CORS data in JSON format
cors_origins()

Retrieves a list of CORS origins.

Returns:List of CORS origins
db_updates(raw_data=False, **kwargs)

Returns the _db_updates feed iterator. The _db_updates feed can be iterated over and once complete can also provide the last sequence identifier of the feed. If necessary, the iteration can be stopped by issuing a call to the stop() method on the returned iterator object.

For example:

# Iterate over a "normal" _db_updates feed
db_updates = client.db_updates()
for db_update in db_updates:
    print(db_update)
print(db_updates.last_seq)

# Iterate over a "continuous" _db_updates feed with additional options
db_updates = client.db_updates(feed='continuous', since='now', descending=True)
for db_update in db_updates:
    if some_condition:
        db_updates.stop()
    print(db_update)
Parameters:
  • raw_data (bool) – If set to True then the raw response data will be streamed otherwise if set to False then JSON formatted data will be streamed. Default is False.
  • descending (bool) – Whether results should be returned in descending order, i.e. the latest event first. By default, the oldest event is returned first.
  • feed (str) – Type of feed. Valid values are continuous, longpoll, and normal. Default is normal.
  • heartbeat (int) – Time in milliseconds after which an empty line is sent during longpoll or continuous if there have been no changes. Must be a positive number. Default is no heartbeat.
  • limit (int) – Maximum number of rows to return. Must be a positive number. Default is no limit.
  • since – Start the results from changes after the specified sequence identifier. In other words, using since excludes from the list all changes up to and including the specified sequence identifier. If since is 0 (the default), or omitted, the request returns all changes. If it is now, only changes made after the time of the request will be emitted.
  • timeout (int) – Number of milliseconds to wait for data before terminating the response. heartbeat supersedes timeout if both are supplied.
  • chunk_size (int) – The HTTP response stream chunk size. Defaults to 512.
Returns:

Feed object that can be iterated over as a _db_updates feed.

disable_cors()

Switches CORS off.

Returns:CORS status in JSON format
generate_api_key()

Creates and returns a new API Key/pass pair.

Returns:API key/pass pair in JSON format
classmethod iam(account_name, api_key, **kwargs)

Create a Cloudant client that uses IAM authentication.

Parameters:
  • account_name – Cloudant account name; or use None and a url kwarg.
  • api_key – IAM authentication API key.
infinite_db_updates(**kwargs)

Returns an infinite (perpetually refreshed) _db_updates feed iterator. If necessary, the iteration can be stopped by issuing a call to the stop() method on the returned iterator object.

For example:

# Iterate over an infinite _db_updates feed
db_updates = client.infinite_db_updates()
for db_update in db_updates:
    if some_condition:
        db_updates.stop()
    print(db_update)
Parameters:
  • descending (bool) – Whether results should be returned in descending order, i.e. the latest event first. By default, the oldest event is returned first.
  • heartbeat (int) – Time in milliseconds after which an empty line is sent if there have been no changes. Must be a positive number. Default is no heartbeat.
  • since – Start the results from changes after the specified sequence identifier. In other words, using since excludes from the list all changes up to and including the specified sequence identifier. If since is 0 (the default), or omitted, the request returns all changes. If it is now, only changes made after the time of the request will be emitted.
  • timeout (int) – Number of milliseconds to wait for data before terminating the response. heartbeat supersedes timeout if both are supplied.
  • chunk_size (int) – The HTTP response stream chunk size. Defaults to 512.
Returns:

Feed object that can be iterated over as a _db_updates feed.

requests_usage(year=None, month=None)

Retrieves Cloudant requests usage data, optionally for a given year and month.

Parameters:
  • year (int) – Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by month.
  • month (int) – Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by year.
Returns:

Requests usage data in JSON format

shared_databases()

Retrieves a list containing the names of databases shared with this account.

Returns:List of database names
update_cors_configuration(enable_cors=True, allow_credentials=True, origins=None, overwrite_origins=False)

Merges existing CORS configuration with updated values.

Parameters:
  • enable_cors (bool) – Enables/disables CORS. Defaults to True.
  • allow_credentials (bool) – Allows authentication credentials. Defaults to True.
  • origins (list) – List of allowed CORS origin(s). Special cases are a list containing a single “*” which will allow any origin and an empty list which will not allow any origin. Defaults to None.
  • overwrite_origins (bool) – Dictates whether the origins list is overwritten of appended to. Defaults to False.
Returns:

CORS configuration update status in JSON format

volume_usage(year=None, month=None)

Retrieves Cloudant volume usage data, optionally for a given year and month.

Parameters:
  • year (int) – Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by month.
  • month (int) – Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by year.
Returns:

Volume usage data in JSON format

class cloudant.client.CouchDB(user, auth_token, admin_party=False, **kwargs)

Bases: dict

Encapsulates a CouchDB client, handling top level user API calls having to do with session and database management.

Maintains a requests.Session for working with the instance specified in the constructor.

Parameters can be passed in to control behavior:

Parameters:
  • user (str) – Username used to connect to CouchDB.
  • auth_token (str) – Authentication token used to connect to CouchDB.
  • admin_party (bool) – Setting to allow the use of Admin Party mode in CouchDB. Defaults to False.
  • url (str) – URL for CouchDB server.
  • encoder (str) – Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder.
  • adapter (requests.HTTPAdapter) – Optional adapter to use for configuring requests.
  • connect (bool) – Keyword argument, if set to True performs the call to connect as part of client construction. Default is False.
  • auto_renew (bool) – Keyword argument, if set to True performs automatic renewal of expired session authentication settings. Default is False.
  • timeout (float) – Timeout in seconds (use float for milliseconds, for example 0.1 for 100 ms) for connecting to and reading bytes from the server. If a single value is provided it will be applied to both the connect and read timeouts. To specify different values for each timeout use a tuple. For example, a 10 second connect timeout and a 1 minute read timeout would be (10, 60). This follows the same behaviour as the Requests library timeout argument. but will apply to every request made using this client.
  • use_basic_auth (bool) – Keyword argument, if set to True performs basic access authentication with server. Default is False.
  • use_iam (bool) – Keyword argument, if set to True performs IAM authentication with server. Default is False. Use iam() to construct an IAM authenticated client.
  • iam_client_id (string) – Keyword argument, client ID to use when authenticating with the IAM token server. Default is None.
  • iam_client_secret (string) – Keyword argument, client secret to use when authenticating with the IAM token server. Default is None.
__delitem__(key, remote=False)

Overrides dictionary __delitem__ behavior to make deleting the database key a proxy for deleting the database. If remote=True then it will delete the database on the remote server, otherwise only the local cached object will be removed.

Parameters:
  • key (str) – Database name of the database to be deleted.
  • remote (bool) – Dictates whether the locally cached database is deleted or a remote request is made to delete the database from the server. Defaults to False.
__getitem__(key)

Overrides dictionary __getitem__ behavior to provide a database instance for the specified key.

If the database instance does not exist locally, then a remote request is made and the database is subsequently added to the local cache and returned to the caller.

If the database instance already exists locally then it is returned and a remote request is not performed.

A KeyError will result if the database does not exist locally or on the server.

Parameters:key (str) – Database name used to retrieve the database object.
Returns:Database object
__setitem__(key, value, remote=False)

Override dictionary __setitem__ behavior to verify that only database instances are added as keys. If remote=True then also create the database remotely if the database does not exist.

Note: The only way to override the default for the remote argument setting it to True is to call __setitem__ directly. A much simpler approach is to use create_database() instead, if your intention is to create a database remotely.

Parameters:
  • key (str) – Database name to be used as the key for the database in the locally cached dictionary.
  • value – Database object to be used in the locally cached dictionary.
  • remote (bool) – Dictates whether the method will attempt to create the database remotely or not. Defaults to False.
all_dbs()

Retrieves a list of all database names for the current client.

Returns:List of database names for the client
basic_auth_str()

Composes a basic http auth string, suitable for use with the _replicator database, and other places that need it.

Returns:Basic http authentication string
change_credentials(user=None, auth_token=None)

Change login credentials.

Parameters:
  • user (str) – Username used to connect to server.
  • auth_token (str) – Authentication token used to connect to server.
connect()

Starts up an authentication session for the client using cookie authentication if necessary.

create_database(dbname, partitioned=False, **kwargs)

Creates a new database on the remote server with the name provided and adds the new database object to the client’s locally cached dictionary before returning it to the caller. The method will optionally throw a CloudantClientException if the database exists remotely.

Parameters:
  • dbname (str) – Name used to create the database.
  • throw_on_exists (bool) – Boolean flag dictating whether or not to throw a CloudantClientException when attempting to create a database that already exists.
  • partitioned (bool) – Create as a partitioned database. Defaults to False.
Returns:

The newly created database object

db_updates(raw_data=False, **kwargs)

Returns the _db_updates feed iterator. While iterating over the feed, if necessary, the iteration can be stopped by issuing a call to the stop() method on the returned iterator object.

For example:

# Iterate over a "longpoll" _db_updates feed
db_updates = client.db_updates()
for db_update in db_updates:
    if some_condition:
        db_updates.stop()
    print(db_update)

# Iterate over a "continuous" _db_updates feed with additional options
db_updates = client.db_updates(feed='continuous', heartbeat=False)
for db_update in db_updates:
    if some_condition:
        db_updates.stop()
    print(db_update)
Parameters:
  • raw_data (bool) – If set to True then the raw response data will be streamed otherwise if set to False then JSON formatted data will be streamed. Default is False.
  • feed (str) – Type of feed. Valid values are continuous, and longpoll. Default is longpoll.
  • heartbeat (bool) – Whether CouchDB will send a newline character on timeout. Default is True.
  • timeout (int) – Number of seconds to wait for data before terminating the response.
  • chunk_size (int) – The HTTP response stream chunk size. Defaults to 512.
Returns:

Feed object that can be iterated over as a _db_updates feed.

delete_database(dbname)

Removes the named database remotely and locally. The method will throw a CloudantClientException if the database does not exist.

Parameters:dbname (str) – Name of the database to delete.
disconnect()

Ends a client authentication session, performs a logout and a clean up.

features()

lazy fetch and cache features

get(key, default=None, remote=False)

Overrides dictionary get behavior to retrieve database objects with support for returning a default. If remote=True then a remote request is made to retrieve the database from the remote server, otherwise the client’s locally cached database object is returned.

Parameters:
  • key (str) – Database name used to retrieve the database object.
  • default (str) – Default database name. Defaults to None.
  • remote (bool) – Dictates whether the locally cached database is returned or a remote request is made to retrieve the database from the server. Defaults to False.
Returns:

Database object

is_iam_authenticated

Show if a client has authenticated using an IAM API key.

Returns:True if client is IAM authenticated. False otherwise.
keys(remote=False)

Returns the database names for this client. Default is to return only the locally cached database names, specify remote=True to make a remote request to include all databases.

Parameters:remote (bool) – Dictates whether the list of locally cached database names are returned or a remote request is made to include an up to date list of databases from the server. Defaults to False.
Returns:List of database names
metadata()

Retrieves the remote server metadata dictionary.

Returns:Dictionary containing server metadata details
session()

Retrieves information about the current login session to verify data related to sign in.

Returns:Dictionary of session info for the current session.

Retrieves the current session cookie.

Returns:Session cookie for the current session
session_login(user=None, passwd=None)

Performs a session login by posting the auth information to the _session endpoint.

Parameters:
  • user (str) – Username used to connect to server.
  • auth_token (str) – Authentication token used to connect to server.
session_logout()

Performs a session logout and clears the current session by sending a delete request to the _session endpoint.