couchbase Package

couchbase Package

class couchbase.Couchbase[source]

The base class for interacting with Couchbase


connect([host, port, username, password, ...]) Connect to a bucket.
static connect(host='localhost', port=8091, username=None, password=None, bucket=None, quiet=False)[source]

Connect to a bucket.

The parameters password and bucket are not optional and will cause a couchbase.exceptions.ArgumentError exception if they are not specified. If username is not given, it will automatically set to the bucket name, as it is expected that you try to connect to a SASL protected bucket, where the username is equal to the bucket name.

  • host (string) – the hostname or IP address of the node
  • port (number) – port of the management API
  • username (string) – the user name to connect to the cluster. It’s the username of the management API. The username could be skipped for protected buckets, the bucket name will be used instead.
  • password (string) – the password of the user or bucket
  • bucket (string) – the bucket name
  • quiet (boolean) – the flag controlling whether to raise an exception when the client executes operations on non-existent keys. If it is False it will raise couchbase.exceptions.NotFoundError exceptions. When set to True the operations will return None silently.
Raise :

couchbase.exceptions.BucketNotFoundError if there is no such bucket to connect to

couchbase.exceptions.ConnectError if the socket wasn’t accessible (doesn’t accept connections or doesn’t respond in time)

couchbase.exceptions.ArgumentError if either the password or the bucket wasn’t specified


instance of couchbase.libcouchbase.Connection

Initialize connection using default options:

from couchbase import Couchbase
cb = Couchbase.connect(username='admin', password='secret',

Connect to protected bucket:

cb = Couchbase.connect(password='secret', bucket='protected')

Connect to a different server on the default port 8091:

cb = Couchbase.connect('', username='admin',
                       password='secret', bucket='mybucket')
class couchbase.libcouchbase.Connection

Connection to a bucket.

Normally it’s initialized through couchbase.Couchbase.connect()

Class attributes


Specify the default format (default: `Couchbase.FMT_JSON’) to encode your data before storing in Couchbase. It uses the flags field to store the format. Possible values are:

  • couchbase.FMT_JSON: Converts the Python object to JSON and stores it as JSON in Couchbase
  • couchbase.FMT_PICKLE: Pickles the Python object and stores it as binary in Couchbase
  • couchbase.FMT_PLAIN: Stores the Python object as is in Couchbase. If it is a string containing valid JSON it will be stored as JSON, else binary.

On a couchbase.libcouchbase.Connection.get() the original value will be returned. This means the JSON will be decoded, respectively the object will be unpickled.


It controlls whether to raise an exception when the client executes operations on non-existent keys (default: False). If it is False it will raise couchbase.exceptions.NotFoundError exceptions. When set to True the operations will return None silently.


add Store an object in Couchbase unless it already exists.
append Append a string to an existing value in Couchbase.
decr Decrement a key in Couchbase.
delete Remove the key-value entry for a given key in Couchbase.
get Obtain an object stored in Couchbase by given key.
incr Increment the numeric value of a key.
prepend Prepend a string to an existing value in Couchbase.
replace Store an object in Couchbase only if it already exists.
set Unconditionally store the object in Couchbase.
stats Request server statistics

Store an object in Couchbase unless it already exists.

Follows the same conventions as set() but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists.

Raise :couchbase.exceptions.KeyExistsError if the key already exists

Append a string to an existing value in Couchbase.

This follows the same conventions as set(), with the caveat that the format argument is unavailable and will always be FMT_PLAIN.

Raise :couchbase.exceptions.NotStoredError if the key does not exist

Decrement a key in Couchbase.

This follows the same conventions as incr(), except the amount is the value which is subtracted ratherthan added to the existing value


Remove the key-value entry for a given key in Couchbase.

  • key (string, dict, or tuple/list) – This can be a single string which is the key to delete, a list of strings, or a dict of strings, with the values being CAS values for each key (see below)
  • cas (int) – The CAS to use for the removal operation. If specified, the key will only be deleted from the server if it has the same CAS as specified. This is useful to delete a key only if its value has not been changed from the version currently visible to the client. If the CAS on the server does not match the one specified, an exception is thrown.
  • quiet (boolean) – Follows the same semantics as quiet in get()
Raise :

couchbase.exceptions.NotFoundError if the key does not exist on the bucket

Raise :

couchbase.exceptions.KeyExistsError if a CAS was specified, but the CAS on the server had changed

Raise :

couchbase.exceptions.ConnectError if the connection was closed


a boolean value or a dictionary of boolean values, depending on whether the key parameter was a string or a collection.

Simple delete:

ok = cb.delete("key")

Don’t complain if key does not exist:

ok = cb.delete("key", quiet = True)

Only delete if CAS matches our version:

value, flags, cas = cb.get("key", extended = True)
cb.delete("key", cas = cas)

Remove multiple keys:

oks = cb.delete(["key1", "key2", "key3"])

Remove multiple keys with CAS:

oks = cb.delete({
    "key1" : cas1,
    "key2" : cas2,
    "key3" : cas3

Obtain an object stored in Couchbase by given key.

  • keys – One or several keys to fetch
  • extended (boolean) – If set to True, the operation will return a named tuple with value, flags and cas, otherwise (by default) it returns just the value.
  • format – explicitly choose the decoder for this key. If none is specified the decoder will automaticall be choosen based on the encoder that was used to store the value. For more information about the formats, see couchbase.libcouchbase.Connection.default_format.
  • quiet (boolean) – causes get to return None instead of raising an exception when the key is not found. It defaults to the value set by couchbase.libcouchbase.Connection.quiet.
Raise :

couchbase.exceptions.NotFoundError if the key is missing in the bucket

Raise :

couchbase.exceptions.ConnectError if the connection closed

Raise :

couchbase.exceptions.ValueFormatError if the value cannot be deserialized with chosen decoder, e.g. if you try to retreive a pickled object in JSON mode.


the value associated with the key or a dict on a multi-get in extended mode.

Simple get:

value = cb.get('key')

Get multiple values:

cb.get(['foo', 'bar', 'baz'])
# [val1, val2, val3]

Extended get:

value, flags, cas = cb.get('key', extended=True)

Extended get using named tuples:

result = cb.get('key', extended=True)
# result.value, result.flags, result.cas

Get multiple values in extended mode:

cb.get(['foo', 'bar'], extended=True)
# {'foo': (val1, flags1, cas1), 'bar': (val2, flags2, cas2)}

Increment the numeric value of a key.

  • key (string or list of strings) – A key or a collection of keys which are to be incremented
  • amount (int) – an amount by which the key should be incremented
  • initial (int or None) – The initial value for the key, if it does not exist. If the key does not exist, this value is used, and amount is ignored. If this parameter is None then no initial value is used
  • ttl (int) – The lifetime for the key, after which it will expire
  • extended (boolean) – If set to true, the return value will be a Result object (similar to whatever get()) returns.
Raise :

couchbase.exceptions.NotFoundError if the key does not exist on the bucket (and initial was None)

Raise :

couchbase.exceptions.DeltaBadvalError if the key exists, but the existing value is not numeric


An integer or dictionary of keys and integers, indicating the current value of the counter. If extended was true, a Result object is used rather than a simple integer. If an operation failed, the value will be None. Check for this as a counter’s value may be 0 (but would not be a failure)

Simple increment:

ok = cb.incr("key")

Increment by 10:

ok = cb.incr("key", amount=10)

Increment by 20, set initial value to 5 if it does not exist:

ok = cb.incr("key", amount=20, initial=5)

Increment three keys, and use the ‘extended’ return value:

kv = cb.incr(["foo", "bar", "baz"], extended=True)
for key, result in kv.items():
    print "Key %s has value %d now" % (key, result.value)

Prepend a string to an existing value in Couchbase.

This follows the same conventions as append()


Store an object in Couchbase only if it already exists.

Follows the same conventions as set(), but the value is stored only if a previous value already exists.

Raise :couchbase.exceptions.NotFoundError if the key does not exist

Unconditionally store the object in Couchbase.

  • key (string or dict) – if it’s a string it’s the key used to reference the value. In case of a dict, it’s a multi-set where the key-value pairs will be stored.
  • value (any) – value to be stored
  • cas (int) – the CAS value for an object. This value is created on the server and is guaranteed to be unique for each value of a given key. This value is used to provide simple optimistic concurrency control when multiple clients or threads try to update an item simultaneously.
  • ttl (int) – the time to live for an object. Values larger than 30*24*60*60 seconds (30 days) are interpreted as absolute times (from midnight, January 1, 1970, a.k.a. the epoch).
  • format – the representation for storing the value in the bucket. If none is specified it will use the default_format. For more info see couchbase.libcouchbase.Connection.default_format.
Raise :

couchbase.exceptions.ArgumentError if an argument is supplied that is not applicable in this context. For example setting the CAS value on a multi set.

Raise :

couchbase.exceptions.ConnectError if the connection closed

Raise :

couchbase.exceptions.KeyExistsError if the key already exists on the server with a different CAS value.

Raise :

couchbase.exceptions.ValueFormatError if the value cannot be serialized with chosen encoder, e.g. if you try to store a dictionaty in plain mode.


(int) the CAS value of the object

Simple set:

cb.set('key', 'value')

Force JSON document format for value:

cb.set('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON)

Perform optimistic locking by specifying last known CAS version:

cb.set('foo', 'bar', cas=8835713818674332672)

Several sets at the same time (mutli-set):

cb.set({'foo': 'bar', 'baz': 'value'})

Request server statistics

Fetches stats from each node in the cluster. Without a key specified the server will respond with a default set of statistical information. It returns the a dict with stats keys and node-value pairs as a value.

Parameters:stats (string or list of string) – One or several stats to query
Raise :couchbase.exceptions.ConnectError if the connection closed
Returns:dict where keys are stat keys and values are host-value pairs

Find out how many items are in the bucket:

total = 0
for key, value in cb.stats()['total_items'].items():
    total += value

Get memory stats (works on couchbase buckets):

# {'mem_used': {...}, ...}


exception couchbase.libcouchbase.CouchbaseError

Base class for errors within the Couchbase Python SDK

  • msg (string) – the error message
  • error (int) – the error code
  • key (string) – the key if it one was involved in the operation that lead to the error
  • status (int) – the HTTP status code if the operation was through HTTP
  • cas – the CAS value
  • operation – The operation that was performed on Couchbase (ADD, SET, REPLACE, APPEND or PREPEND)
exception couchbase.exceptions.ArgumentError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Invalid argument

A given argument is invalid or must be set

exception couchbase.exceptions.ValueFormatError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Failed to decode or encode value

The following exceptions are caused by the underlying libcouchbase.

exception couchbase.exceptions.AuthError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Authentication failed

You provided an invalid username/password combination.

exception couchbase.exceptions.DeltaBadvalError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The given value is not a number

The server detected that operation cannot be executed with requested arguments. For example, when incrementing not a number.

exception couchbase.exceptions.TooBigError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Object too big

The server reported that this object is too big

exception couchbase.exceptions.BusyError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The cluster is too busy

The server is too busy to handle your request right now. please back off and try again at a later time.

exception couchbase.exceptions.InternalError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Internal Error

Internal error inside the library. You would have to destroy the instance and create a new one to recover.

exception couchbase.exceptions.InvalidError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Invalid arguments specified

exception couchbase.exceptions.NoMemoryError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The server ran out of memory

exception couchbase.exceptions.RangeError[source]

Bases: couchbase.libcouchbase.CouchbaseError

An invalid range specified

exception couchbase.exceptions.LibcouchbaseError[source]

Bases: couchbase.libcouchbase.CouchbaseError

A generic error

exception couchbase.exceptions.TemporaryFailError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Temporary failure (on server)

The server tried to perform the requested operation, but failed due to a temporary constraint. Retrying the operation may work.

exception couchbase.exceptions.KeyExistsError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The key already exists (with another CAS value)

exception couchbase.exceptions.NotFoundError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The key does not exist

exception couchbase.exceptions.DlopenFailedError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Failed to open shared object

exception couchbase.exceptions.DlsymFailedError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Failed to locate the requested symbol in the shared object

exception couchbase.exceptions.NetworkError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Network error

A network related problem occured (name lookup, read/write/connect etc)

exception couchbase.exceptions.NotMyVbucketError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The vbucket is not located on this server

The server who received the request is not responsible for the object anymore. (This happens during changes in the cluster topology)

exception couchbase.exceptions.NotStoredError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The object was not stored on the server

exception couchbase.exceptions.NotSupportedError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Not supported

The server doesn’t support the requested command. This error differs from couchbase.exceptions.UnknownCommandError by that the server knows about the command, but for some reason decided to not support it.

exception couchbase.exceptions.UnknownCommandError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The server doesn’t know what that command is

exception couchbase.exceptions.UnknownHostError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The server failed to resolve the requested hostname

exception couchbase.exceptions.ProtocolError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Protocol error

There is something wrong with the datastream received from the server

exception couchbase.exceptions.TimeoutError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The operation timed out

exception couchbase.exceptions.ConnectError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Failed to connect to the requested server

exception couchbase.exceptions.BucketNotFoundError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The requested bucket does not exist

exception couchbase.exceptions.ClientNoMemoryError[source]

Bases: couchbase.libcouchbase.CouchbaseError

The client ran out of memory

exception couchbase.exceptions.ClientTemporaryFailError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Temporary failure (on client)

The client encountered a temporary error (retry might resolve the problem)

exception couchbase.exceptions.BadHandleError[source]

Bases: couchbase.libcouchbase.CouchbaseError

Invalid handle type

The requested operation isn’t allowed for given type.

Table Of Contents

Previous topic

Couchbase Python Client Library Documentation

This Page