Python Client Library

Couchbase Server for Python Development

New for Couchbase Server 2.0, we have a developer preview of a client library compatible with both Couchbase Server 1.8 and Couchbase Server 2.0.  This developer preview coordinates with the REST interface from Couchbase Server to adjust to cluster topology changes as needed.

 

Step 0: Get a Server

Get & Install Couchbase Server. Come back here when you're done.

Step 1: Get a Client Library

 

Step 1.0: Get libcouchbase

Since the Python extension builds on the 2.0 version of the Couchbase C SDK you will need to get it. The C SDK downloads and instructions are here.  Be sure to install the header files, which are frequently in a -dev or -devel package, depending on your Operating System.

Note if you have an earlier version of the Couchbase C SDK, remove it before you install the new C SDK.

Step 1.1: Install the Python SDK

 

The easiest way to get the Couchbase Python Client Library is to use PIP.

pip install couchbase

Step 2: Try it out!

Setup

Once the Couchbase Python Client Library has been installed, it's easy to get started.  Create a new Python file and add your import statements, or you can just follow along in the python shell.

#!/usr/bin/env python

from couchbase import Couchbase

Creating a Couchbase Client Instance

To create a Couchbase client instance, call the connect method with the host, port, username, password and bucket name.

cb = Couchbase.connect(bucket='default')

The default Couchbase Server installation creates a bucket named "default" without a password, which in this case is blank.  If you created an authenticated bucket, you should specify those values in place of the default settings above. 

The construction of a Couchbase instance does require some overhead as the cluster topology is discovered, so as a best practice you should retain the client object for multiple requests. If using threads, note that you must not use the same instance from multiple threads concurrently (though one instance can be shared if proper locking is used).

CRUD Operations

The primary CRUD API used by the Python Client is relatively straightforward. You create and update documents by supplying a key and value. You retrieve or remove documents by supplying a key.  For example, consider the JSON document that you'll find in the "beer-sample" bucket that's available when you install Couchbase Server and setup your cluster.  The key "new_holland_brewing_company-sundog" is associated with the beer document below.

{
    "brewery_id": "new_holland_brewing_company",
    "category": "North American Ale",
    "updated": "2010-07-22 20:00:20",
    "name": "Sundog",
    "upc": 0,
    "srm": 0.0,
    "style": "American-Style Amber/Red Ale",
    "abv": 5.25,
    "type": "beer",
    "ibu": 0.0,
    "description": "Sundog is an amber ale as deep as the copper glow of a Lake Michigan sunset. Its biscuit malt give Sundog a toasty character and a subtle malty sweetness. Sundog brings out the best in grilled foods, caramelized onions, nutty cheese, barbecue, or your favorite pizza."
}

Note that credentials and bucket selection change to use the beer sample database.  If you do not have that sample database loaded, you may add it through Settings -> Sample Buckets. This will replace the previously created connection.

cb = Couchbase.connect(bucket='beer-sample')

To retrieve this document, you simply call the get method of the bucket.  The get method returns the Result of the object.

Getting Documents

result = cb.get('new_holland_brewing_company-sundog')

If you print out the result, you will see the value along with some metadata:

print result

Which outputs:

ValueResult<RC=0x0, Key=new_holland_brewing_company-sundog, Value={u'brewery_id': u'new_holland_brewing_company', u'category': u'North American Ale', u'updated': u'2010-07-22 20:00:20', u'name': u'Sundog', u'upc': 0, u'srm': 0.0, u'style': u'American-Style Amber/Red Ale', u'abv': 5.25, u'type': u'beer', u'ibu': 0.0, u'description': u'Sundog is an amber ale as deep as the copper glow of a Lake Michigan sunset. Its biscuit malt give Sundog a toasty character and a subtle malty sweetness. Sundog brings out the best in grilled foods, caramelized onions, nutty cheese, barbecue, or your favorite pizza.'}, CAS=0x66ce536e72dc0000, Flags=0x0>
You can access the actual value by using the Result's object value property. We will use the pprint module (in the standard library) to give us a nice representation:
from pprint import pprint
pprint(result.value, indent=4)

Which outputs:

{   u'abv': 5.25,
    u'brewery_id': u'new_holland_brewing_company',
    u'category': u'North American Ale',
    u'description': u'Sundog is an amber ale as deep as the copper glow of a Lake Michigan sunset. Its biscuit malt give Sundog a toasty character and a subtle malty sweetness. Sundog brings out the best in grilled foods, caramelized onions, nutty cheese, barbecue, or your favorite pizza.',
    u'ibu': 0.0,
    u'name': u'Sundog',
    u'srm': 0.0,
    u'style': u'American-Style Amber/Red Ale',
    u'type': u'beer',
    u'upc': 0,
    u'updated': u'2010-07-22 20:00:20'}

Storing Documents

Documents are typically stored in JSON format, which is the default storage format of the client. As such, it will convert most native Python types to their JSON equivalent. Of course, you're not forced to store items as JSON - but storing items as JSON allows them to be indexed by map-reduce queries (see below)

To add a JSON document, first create a dictionary.

new_beer = {
   "name": "Old Yankee Ale",
   "abv": 5.00,
   "ibu": 0,
   "srm": 0,
   "upc": 0,
   "type": "beer",
   "brewery_id": "cottrell_brewing_co",
   "updated": "2012-08-30 20:00:20",
   "description": ".A medium-bodied Amber Ale",
   "style": "American-Style Amber",
   "category": "North American Ale"
}

For a key, we'll concatenate the brewery name in lower case, followed by a dash, followed by the beer name. We'll also normalize the name by replacing spaces with underscore and making it all lowercase. By doing so, we can directly retrieve documents by key (not just through views, which will be covered later) since we can directly determine the key name.

key = "{0}-{1}".format(
        new_beer['brewery_id'],
        new_beer['name'].replace(' ', '_').lower())
# key is "cottrell_brewing_co-old_yankee_ale"

With this new key, the JSON document may easily be stored.

result = cb.set(key, new_beer)

The set method will replace a key if it exists or add it if it does not, and will serialize its value to JSON by default. There are also individual add and replace methods.  The return value is a common Result object indicating status and other metadata, including its CAS -- a value indicating the Document's current version.

print result
OperationResult<RC=0x0, Key=cottrell_brewing_co-old_yankee_ale, Value=None, CAS=0x888b2ffcd1f00100>

 

You may also remove the document by calling delete with the key:

cb.delete(key)

 

Working with Views

Note! The view API is not yet stable - the behavior and APIs will change.

Map/Reduce Views are used to create queryable, secondary indexes in Couchbase Server.  The primary index for documents is the key you use when performing the standard CRUD methods described above.  See the view documentation for more information on writing views. 

For this example, a by_name view in a beer design document will be queried.  This view simply checks whether a document is a beer and has a name.  If it does, it emits the beer's name into the index.  This view will allow for beers to be queried for by name.  For example, it's now possible to ask the question "What beers start with A?"

function (doc, meta) {
  if (doc.type && doc.type == "beer" && doc.name) {    
     emit(doc.name, null);
  }
}

Querying a view through the Python client is performed through the _view method.

result = cb._view("beer", "by_name")
The view method returns a list with dictionary entries for each row in the view's results.  Iterating over the results of the view, the "id" property of the row (currently the unicode id must be converted to an ASCII string) can be used to retrieve the original document. 
for row in result.value["rows"]:
    id = row["id"]
    beer = cb.get(row["id"]).value
    print beer["name"]
Finally, the view results can be modified by specifying keyword arguments when first calling the view method.
view = cb._view("beer","by_name", {'limit':'10', 'key':json.dumps("Sundog")})

Then Learn More:

The full getting started guide will cover additional getting started information. From there, move on to the tutorial, which will show how to build a full application on Couchbase Server with a JSON dataset, sample views, and modifying data.