Python SDK 2.0

Python SDK 2.0

The Couchbase Python client allows you to connect to a Couchbase cluster from Python. It is written as a fast C extension with support for a traditional synchronous API, as well as gevent and twisted APIs for high performance asynchronous programming.

Important: This document is for the 2.x version of the Python SDK. If you are not using the 2.x version, please refer to the Python SDK 1.2 documentation.

To download the Python client, go to the download page.

Here's a sampling of what you can do with the Couchbase Python SDK:


To connect to a bucket, just import the Bucket class from the couchbase.bucket package. The Bucket object represents a connection to a Couchbase bucket. To instantiate the bucket object, pass it the location of the cluster and the bucket you with to connect to. The following shows how to connect to a bucket on localhost.

from couchbase.bucket import Bucket
bucket = Bucket('couchbase://localhost/default')


In most cases, you perform operations by invoking the relevant method while passing the key, any data and meta information that goes with it. Operations return a Result object containing the value and other information about the item.

Here is an example of performing a get operations:

rv = bucket.get('foo')
print rv.value

Additionally, sometimes more information beyond the key is needed for an operation, as seen here:

bucket.insert('some_key', { 'some': 'value' })

Performing N1QL Queries

Couchbase N1QL queries are performed by creating a N1QLQuery object and passing that to the n1ql_query() method:
from couchbase.n1ql import N1QLQuery
query = N1QLQuery("SELECT airportname, city, country FROM `travel-sample `
                  "WHERE type=\"airport\" AND city=my_city", my_city="Reno")
for row in bucket.n1ql_query(query):
    print row

Performing MapReduce Queries

In addition to the basic operations that are available, more methods are provided to perform queries against your data. These queries allow you to ask questions like "What beers start with A?" rather than simply "Give me the beer that is called Aaas_Frankl." This is possible through the use of the Couchbase MapReduce views engine. The following is an example of performing a view query:

for row in bucket.query('beer', 'by_name', limit=3):
    print row