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.
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.
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.
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.
To retrieve this document, you simply call the get method of the bucket. The get method returns the Result of the object.
Getting Documents
If you print out the result, you will see the value along with some metadata:
Which outputs:
pprint(result.value, indent=4)
Which outputs:
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.
"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.
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.
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.
You may also remove the document by calling delete with the 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?"
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.
id = row["id"]
beer = cb.get(row["id"]).value
print beer["name"]
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.