Twisted Interface

Warning

The async APIs below are from SDK2 and currently only available from the couchbase_v2 legacy support package. They will be updated to support SDK3 shortly. See JIRA.

The Twisted interface is for use with the Twisted Python event and networking library which may be found at http://www.twistedmatrix.com. This documentation contains the API reference for how to use the txcouchbase module with Twisted.

For the most part, the txcouchbase API functions like its synchronous counterpart, Bucket, except for its asynchronous nature. Where the synchronous API returns a Result object, the txcouchbase API returns a Deferred which will have its callback invoked with a result.

As such, we will omit the mentions of the normal key value operations, which function identially to their synchronous conterparts documented in the Bucket class.

The Bucket interface for Twisted is subclassed from the lower-level RawBucket which returns AsyncResult objects rather than Deferred objects. This is largely due to performance reasons (Deferreds result in a 3x performance slowdown).

class txcouchbase.bucket.RawBucket[source]
__init__(connstr=None, **kwargs)[source]

Bucket subclass for Twisted. This inherits from the ‘AsyncBucket’ class, but also adds some twisted-specific logic for hooking on a connection.

registerDeferred(event, d)[source]

Register a defer to be fired at the firing of a specific event.

Parameters
  • event (Deferred) – Currently supported values are connect. Another value may be _dtor which will register an event to fire when this object has been completely destroyed.

  • event – The defered to fire when the event succeeds or failes

If this event has already fired, the deferred will be triggered asynchronously.

Example:

def on_connect(*args):
    print("I'm connected")
def on_connect_err(*args):
    print("Connection failed")

d = Deferred()
cb.registerDeferred('connect', d)
d.addCallback(on_connect)
d.addErrback(on_connect_err)
Raise

ValueError if the event name is unrecognized

connect()[source]

Short-hand for the following idiom:

d = Deferred()
cb.registerDeferred('connect', d)
return d
Returns

A Deferred

defer(opres)[source]

Converts a raw couchbase_core.results.AsyncResult object into a Deferred.

This is shorthand for the following “non-idiom”:

d = Deferred()
opres = cb.upsert("foo", "bar")
opres.callback = d.callback

def d_err(res, ex_type, ex_val, ex_tb):
    d.errback(opres, ex_type, ex_val, ex_tb)

opres.errback = d_err
return d
Parameters

opres (couchbase_core.results.AsyncResult) – The operation to wrap

Returns

a Deferred object.

Example:

opres = cb.upsert("foo", "bar")
d = cb.defer(opres)
def on_ok(res):
    print("Result OK. Cas: {0}".format(res.cas))
d.addCallback(opres)
connected

Boolean read only property indicating whether this instance has been connected.

Note that this will still return true even if it is subsequently closed via _close()

class txcouchbase.bucket.Bucket[source]
__init__(*args, **kwargs)[source]

This class inherits from RawBucket. In addition to the connection methods, this class’ data access methods return Deferreds instead of AsyncResult objects.

Operations such as get() or set() will invoke the Deferred.callback with the result object when the result is complete, or they will invoke the Deferred.errback with an exception (or Failure) in case of an error. The rules of the quiet attribute for raising exceptions apply to the invocation of the errback. This means that in the case where the synchronous client would raise an exception, the Deferred API will have its errback invoked. Otherwise, the result’s success field should be inspected.

Likewise multi operations will be invoked with a MultiResult compatible object.

Some examples:

Using single items:

d_set = cb.upsert("foo", "bar")
d_get = cb.get("foo")

def on_err_common(*args):
    print("Got an error: {0}".format(args)),
def on_set_ok(res):
    print("Successfuly set key with CAS {0}".format(res.cas))
def on_get_ok(res):
    print("Successfuly got key with value {0}".format(res.value))

d_set.addCallback(on_set_ok).addErrback(on_err_common)
d_get.addCallback(on_get_ok).addErrback(on_get_common)

# Note that it is safe to do this as operations performed on the
# same key are *always* performed in the order they were scheduled.

Using multiple items:

d_get = cb.get_multi(("Foo", "bar", "baz"))
def on_mres(mres):
    for k, v in mres.items():
        print("Got result for key {0}: {1}".format(k, v.value))
d_get.addCallback(on_mres)
queryAll(*args, **kwargs)

Returns a Deferred object which will have its callback invoked with a BatchedView when the results are complete.

Parameters follow conventions of query().

Example:

d = cb.queryAll("beer", "brewery_beers")
def on_all_rows(rows):
    for row in rows:
       print("Got row {0}".format(row))

d.addCallback(on_all_rows)
queryEx(viewcls, *args, **kwargs)

Query a view, with the viewcls instance receiving events of the query as they arrive.

Parameters

viewcls (type) – A class (derived from AsyncViewBase) to instantiate

Other arguments are passed to the standard query method.

This functions exactly like the query() method, except it automatically schedules operations if the connection has not yet been negotiated.

n1qlQueryAll(*args, **kwargs)

Execute a N1QL query, retrieving all rows.

This method returns a Deferred object which is executed with a N1QLRequest object. The object may be iterated over to yield the rows in the result set.

This method is similar to n1ql_query() in its arguments.

Example:

def handler(req):
    for row in req:
        # ... handle row

d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`,
                'Reno')
d.addCallback(handler)
Returns

A Deferred

See also

n1ql_query()

n1qlQueryEx(cls, *args, **kwargs)

Execute a N1QL statement providing a custom handler for rows.

This method allows you to define your own subclass (of AsyncN1QLRequest) which can handle rows as they are received from the network.

Parameters
  • cls – The subclass (not instance) to use

  • args – Positional arguments for the class constructor

  • kwargs – Keyword arguments for the class constructor

See also

queryEx(), around which this method wraps

class txcouchbase.bucket.BatchedView[source]
__iter__()

Iterate over the rows in this resultset

__init__(*args, **kwargs)[source]

Iterator/Container object for a single-call row-based results.

This functions as an iterator over all results of the query, once the query has been completed.

Additional metadata may be obtained by examining the object. See Views for more details.

You will normally not need to construct this object manually.