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, 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: ValueErrorif the event name is unrecognized- event (
-
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.results.AsyncResultobject into aDeferred.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.results.AsyncResult) – The operation to wrapReturns: a Deferredobject.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 returnDeferredsinstead ofAsyncResultobjects.Operations such as
get()orset()will invoke theDeferred.callbackwith the result object when the result is complete, or they will invoke theDeferred.errbackwith an exception (orFailure) in case of an error. The rules of thequietattribute for raising exceptions apply to the invocation of theerrback. This means that in the case where the synchronous client would raise an exception, the Deferred API will have itserrbackinvoked. Otherwise, the result’ssuccessfield should be inspected.Likewise multi operations will be invoked with a
MultiResultcompatible 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.addCallback(mres)
-
queryAll(*args, **kwargs)¶ Returns a
Deferredobject which will have its callback invoked with aBatchedViewwhen 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
viewclsinstance receiving events of the query as they arrive.Parameters: viewcls (type) – A class (derived from AsyncViewBase) to instantiateOther 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
Deferredobject which is executed with aN1QLRequestobject. 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 DeferredSee also
-
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
-