Choosing an API

    The Couchbase Python SDK offers both asyncio and Twisted APIs for async operation.

    We will cover the asyncio API here initially. Twisted documentation will be added shortly.

    For asyncio: All operations return a Future[T] where T is the return type, with T generally being the same type as the synchronous equivalent. (Note, this genericisation of the Future type is not supported widely, yet, but the object returned is indeed a Future the value of which is of type T) This is equivalent to the operation being marked async fn(…​)→T, and await ing the result will wait for the operation to complete or fail.

    Future s are evaluated asynchronously using the familiar await keyword, and run in a blocking method. If a Future is awaited, the method awaiting the task must have the async keyword in its signature. More information can be found in Python’s asyncio documentation.

    Note: All examples on this page start with initiating a Cluster object and then opening the default Bucket and Collection:

    import acouchbase.cluster
    import couchbase.cluster
    import couchbase.auth
    cluster = acouchbase.cluster.Cluster("couchbase://localhost", couchbase.cluster.ClusterOptions(couchbase.auth.PasswordAuthenticator("user", "password")))
    bucket = cluster.bucket("default")
    await bucket.on_connect()
    collection = bucket.default_collection()

    Asynchronous Programming using await

    This is the most common and basic way for consuming Couchbase operations asynchronously via asyncio:

    upsert_result = await collection.upsert("doc1", dict(name="Ted", age=80))
    get_result = await collection.get("doc1")
    person = get_result.content

    Note that in the upsert method above, an exception will be thrown if the operation fails; if it succeeds then the result will be an MutationResult that contains the CAS value for reuse, otherwise it can be ignored. get returns a GetResult if it succeeds, you’ll then have to use content or content_as to read the returned value.