Twisted Interface

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, couchbase, 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 Cluster Bucket, and Collection classes.

The TxDeferredClient mixin for Twisted is subclassed from the lower-level TxRawClient which returns AsyncGetResult etc objects rather than Deferred objects. This is largely due to performance reasons (Deferreds result in a 3x performance slowdown).

class txcouchbase.cluster.TxRawClientMixin[source]
__init__(connstr=None, *args, **kwargs)[source]

Client mixin for Twisted. This inherits from an ‘AsyncClient’ class, but also adds some twisted-specific logic for hooking on a connection.

Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

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

on_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.cluster.TxDeferredClientMixin[source]
__init__(connstr=None, *args, **kwargs)[source]

This mixin inherits from TxRawClientMixin. In addition to the connection methods, this class’ data access methods return Deferreds instead of Result 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 MultiResultBase 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)
Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

class txcouchbase.cluster.TxRawCluster[source]
__init__(connstr=None, *args, **kwargs)[source]
Client mixin for Twisted. This inherits from an ‘AsyncClient’ class,

but also adds some twisted-specific logic for hooking on a connection.

Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

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

Executes an Analytics query against the remote cluster and returns a AnalyticsResult with the results of the query.

Parameters
  • statement – the analytics statement to execute

  • options – the optional parameters that the Analytics service takes based on the Analytics RFC.

Returns

An AnalyticsResult object with the results of the query or error message if the query failed on the server.

Raise

AnalyticsException errors associated with the analytics query itself. Also, any exceptions raised by the underlying platform - TimeoutException for example.

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

Experimental Method

Execute a Search query, retrieving all rows.

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

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

Example:

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

d = cb.search('name', ft.MatchQuery('nosql'), limit=10)
d.addCallback(handler)
Returns

A Deferred

See also

search()

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

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()

query_ex(cls, *args, **kwargs)[source]

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.cluster.TxCluster[source]
__init__(connection_string, *args, **kwargs)[source]
This mixin inherits from TxRawClientMixin.

In addition to the connection methods, this class’ data access methods return Deferreds instead of Result 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 MultiResultBase 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)
Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

class txcouchbase.cluster.TxRawBucket[source]
__init__(*args, **kwargs)[source]
Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

class txcouchbase.cluster.TxBucket[source]
view_query(*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)
view_query_ex(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.

class txcouchbase.cluster.TxRawCollection[source]
__init__(connstr=None, *args, **kwargs)

Client mixin for Twisted. This inherits from an ‘AsyncClient’ class, but also adds some twisted-specific logic for hooking on a connection.

Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

class txcouchbase.cluster.TxCollection[source]
__init__(connstr=None, *args, **kwargs)

This mixin inherits from TxRawClientMixin. In addition to the connection methods, this class’ data access methods return Deferreds instead of Result 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 MultiResultBase 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)
Warning

This is an internal API call.

Components external to Couchbase Python Client should not rely on it is not intended for use outside the module, even to other Couchbase components.

class txcouchbase.cluster.BatchedViewResult[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.

class txcouchbase.cluster.BatchedQueryResult[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.

class txcouchbase.cluster.BatchedAnalyticsResult[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.

class txcouchbase.cluster.BatchedSearchResult[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.