Differences between revisions 8 and 9
Revision 8 as of 2008-11-05 01:21:32
Size: 7319
Editor: MartinCzura
Comment: redirect
Revision 9 as of 2009-09-20 21:44:48
Size: 7319
Editor: localhost
Comment: converted to 1.6 markup
No differences found!

Getting started with Python and the CouchDB API.

Library

couchdb-python

The code for the Python library can be obtained from:

From a terminal window:

$ wget http://peak.telecommunity.com/dist/ez_setup.py
$ sudo python ez_setup.py
$ wget http://pypi.python.org/packages/2.5/C/CouchDB/CouchDB-0.4-py2.5.egg
$ sudo easy_install CouchDB-0.4-py2.5.egg

This first downloads and installs the ez_setup.py script which runs python .egg files. The second part downloads the .egg file for CouchDB and installs it along with its dependencies.

pouch

Tutorial on using couchdb-python with Django

A tutorial on using Django (a Python framework) with CouchDb can be found at

Alternatively you can view just the source for that example at

Example Wrapper Class

Demonstration of basic API-interaction using Python.

   1 #! /usr/bin/python2.4
   2 
   3 import httplib, simplejson  # http://cheeseshop.python.org/pypi/simplejson
   4                             # Here only used for prettyprinting
   5 
   6 def prettyPrint(s):
   7     """Prettyprints the json response of an HTTPResponse object"""
   8 
   9     # HTTPResponse instance -> Python object -> str
  10     print simplejson.dumps(simplejson.loads(s.read()), sort_keys=True, indent=4)
  11 
  12 class Couch:
  13     """Basic wrapper class for operations on a couchDB"""
  14 
  15     def __init__(self, host, port=5984, options=None):
  16         self.host = host
  17         self.port = port
  18 
  19     def connect(self):
  20         return httplib.HTTPConnection(self.host, self.port) # No close()
  21 
  22     # Database operations
  23 
  24     def createDb(self, dbName):
  25         """Creates a new database on the server"""
  26 
  27         r = self.put(''.join(['/',dbName,'/']), "")
  28         prettyPrint(r)
  29 
  30     def deleteDb(self, dbName):
  31         """Deletes the database on the server"""
  32 
  33         r = self.delete(''.join(['/',dbName,'/']))
  34         prettyPrint(r)
  35 
  36     def listDb(self):
  37         """List the databases on the server"""
  38 
  39         prettyPrint(self.get('/_all_dbs'))
  40 
  41     def infoDb(self, dbName):
  42         """Returns info about the couchDB"""
  43         r = self.get(''.join(['/', dbName, '/']))
  44         prettyPrint(r)
  45 
  46     # Document operations
  47 
  48     def listDoc(self, dbName):
  49         """List all documents in a given database"""
  50 
  51         r = self.get(''.join(['/', dbName, '/', '_all_docs']))
  52         prettyPrint(r)
  53 
  54     def openDoc(self, dbName, docId):
  55         """Open a document in a given database"""
  56         r = self.get(''.join(['/', dbName, '/', docId,]))
  57         prettyPrint(r)
  58 
  59     def saveDoc(self, dbName, body, docId=None):
  60         """Save/create a document to/in a given database"""
  61         if docId:
  62             r = self.put(''.join(['/', dbName, '/', docId]), body)
  63         else:
  64             r = self.post(''.join(['/', dbName, '/']), body)
  65         prettyPrint(r)
  66 
  67     def deleteDoc(self, dbName, docId):     
  68         # XXX Crashed if resource is non-existent; not so for DELETE on db. Bug?
  69         # XXX Does not work any more, on has to specify an revid 
  70         #     Either do html head to get the recten revid or provide it as parameter
  71         r = self.delete(''.join(['/', dbName, '/', docId]))
  72         prettyPrint(r)
  73 
  74     # Basic http methods
  75 
  76     def get(self, uri):
  77         c = self.connect()
  78         headers = {"Accept": "application/json"}
  79         c.request("GET", uri, None, headers)
  80         return c.getresponse()
  81 
  82     def post(self, uri, body):
  83         c = self.connect()
  84         headers = {"Content-type": "application/json"}
  85         c.request('POST', uri, body, headers)
  86         return c.getresponse()
  87 
  88     def put(self, uri, body):
  89         c = self.connect()
  90         if len(body) > 0:
  91             headers = {"Content-type": "application/json"}
  92             c.request("PUT", uri, body, headers)
  93         else:
  94             c.request("PUT", uri, body)
  95         return c.getresponse()
  96 
  97     def delete(self, uri):
  98         c = self.connect()
  99         c.request("DELETE", uri)
 100         return c.getresponse()

Usage Example

   1 def test():
   2     foo = Couch('localhost', '5984')
   3 
   4     print "\nCreate database 'mydb':"
   5     foo.createDb('mydb')
   6 
   7     print "\nList databases on server:"
   8     foo.listDb()
   9 
  10     print "\nCreate a document 'mydoc' in database 'mydb':"
  11     doc = """
  12     {
  13         "value":
  14         {
  15             "Subject":"I like Planktion",
  16             "Author":"Rusty",
  17             "PostedDate":"2006-08-15T17:30:12-04:00",
  18             "Tags":["plankton", "baseball", "decisions"],
  19             "Body":"I decided today that I don't like baseball. I like plankton."
  20         }
  21     }
  22     """
  23     foo.saveDoc('mydb', doc, 'mydoc')
  24 
  25     print "\nCreate a document, using an assigned docId:"
  26     foo.saveDoc('mydb', doc)
  27 
  28     print "\nList all documents in database 'mydb'"
  29     foo.listDoc('mydb')
  30 
  31     print "\nRetrieve document 'mydoc' in database 'mydb':"
  32     foo.openDoc('mydb', 'mydoc')
  33 
  34     print "\nDelete document 'mydoc' in database 'mydb':"
  35     foo.deleteDoc('mydb', 'mydoc')
  36 
  37     print "\nList all documents in database 'mydb'"
  38     foo.listDoc('mydb')
  39 
  40     print "\nList info about database 'mydb':"
  41     foo.infoDb('mydb')
  42 
  43     print "\nDelete database 'mydb':"
  44     foo.deleteDb('mydb')
  45 
  46     print "\nList databases on server:"
  47     foo.listDb()
  48 
  49 if __name__ == "__main__":
  50     test()

Sample Output

   1 Create database 'mydb':
   2 {
   3     "ok": true
   4 }
   5 
   6 List databases on server:
   7 [
   8     "mydb"
   9 ]
  10 
  11 Create a document 'mydoc' in database 'mydb':
  12 {
  13     "_id": "mydoc",
  14     "_rev": 362213977,
  15     "ok": true
  16 }
  17 
  18 Create a document, using an assigned docId:
  19 {
  20     "_id": "CF29360495B2AAB44C7E43E5752A5123",
  21     "_rev": 627930386,
  22     "ok": true
  23 }
  24 
  25 List all documents in database 'mydb'
  26 {
  27     "rows": [
  28         {
  29             "_id": "CF29360495B2AAB44C7E43E5752A5123",
  30             "_rev": 627930386
  31         },
  32         {
  33             "_id": "mydoc",
  34             "_rev": 362213977
  35         }
  36     ],
  37     "view": "_all_docs"
  38 }
  39 
  40 Retrieve document 'mydoc' in database 'mydb':
  41 {
  42     "_id": "mydoc",
  43     "_rev": 362213977,
  44     "value": {
  45         "Author": "Rusty",
  46         "Body": "I decided today that I don't like baseball. I like plankton.",
  47         "PostedDate": "2006-08-15T17:30:12-04:00",
  48         "Subject": "I like Planktion",
  49         "Tags": [
  50             "plankton",
  51             "baseball",
  52             "decisions"
  53         ]
  54     }
  55 }
  56 
  57 Delete document 'mydoc' in database 'mydb':
  58 {
  59     "_rev": 3811288472,
  60     "ok": true
  61 }
  62 
  63 List all documents in database 'mydb'
  64 {
  65     "rows": [
  66         {
  67             "_id": "CF29360495B2AAB44C7E43E5752A5123",
  68             "_rev": 627930386
  69         }
  70     ],
  71     "view": "_all_docs"
  72 }
  73 
  74 List info about database 'mydb':
  75 {
  76     "db_name": "mydb",
  77     "doc_count": 1,
  78     "update_seq": 3
  79 }
  80 
  81 Delete database 'mydb':
  82 {
  83     "ok": true
  84 }
  85 
  86 List databases on server:
  87 []

GettingStartedWithPython (last edited 2009-09-20 21:44:48 by localhost)