Differences between revisions 21 and 22
Revision 21 as of 2011-11-23 14:53:49
Size: 8374
Editor: JanLehnardt
Comment: add ContributorGroup link
Revision 22 as of 2013-10-28 10:00:42
Size: 8419
Comment: changed couchquery URL to http://nicolaisi.github.io/couchquery/ as mikeal transferred ownership to nicolaisi
Deletions are marked like this. Additions are marked like this.
Line 46: Line 46:
 . http://mikeal.github.com/couchquery/ A simple and dynamic access to CouchDB.

. http://nicolaisi.github.io/couchquery/

The official documentation has moved to http://docs.couchdb.org — The transition is not 100% complete, but http://docs.couchdb.org should be seen as having the latest info. In some cases, the wiki still has some more or older info on certain topics inside CouchDB.

You need to be added to the ContributorsGroup to edit the wiki. But don't worry! Just email any Mailing List or grab us on IRC and let us know your user name.

Getting started with Python and the CouchDB API.

Library

couchdbkit

Start using Couchdbkit by reading the Getting Started tutorial.

For django use the django extension of couchdbkit. Other extension exists for formalchemy.

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.6/C/CouchDB/CouchDB-0.8-py2.6.egg
$ sudo easy_install CouchDB-0.8-py2.6.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.

You can find the documentation here, although make sure you use the latest version. A brief introduction:

import couchdb

couch = couchdb.Server() # Assuming localhost:5984
# If your CouchDB server is running elsewhere, set it up like this:
couch = couchdb.Server('http://example.com:5984/')

# select database
db = couch['mydb']

#create a document and insert it into the db:
doc = {'foo': 'bar'}
db.save(doc)

couchquery

A simple and dynamic access to CouchDB.

couchshelve

An implementation of the python 'shelve' API using couchquery as a backend

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. (note: as of python 2.6, one can use "import json" for the same functionality in this script.)

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

Getting_started_with_Python (last edited 2013-10-28 10:00:42 by NicholasJerome)