A simple example of Python working with a CouchDB database

  • 2020-04-02 14:37:46
  • OfStack

Install the python couchDb library:

https://pypi.python.org/pypi/CouchDB/0.10

Connect to server


>>> import couchdb
>>> couch = couchdb.Server('http://example.com:5984/')

Create a database

>>> db = couch.create('test') # New database
>>> db = couch['mydb'] # Use an existing database

Create the document and insert it into the database:

>>> doc = {'foo': 'bar'}
>>> db.save(doc)
('e0658cab843b59e63c8779a9a5000b01', '1-4c6114c65e295552ab1019e2b046b10e')
>>> doc
{'_rev': '1-4c6114c65e295552ab1019e2b046b10e', 'foo': 'bar', '_id': 'e0658cab843b59e63c8779a9a5000b01'}

The save() method returns the '_id','_rev' fields
Query the database by id

>>> db['e0658cab843b59e63c8779a9a5000b01']
<Document 'e0658cab843b59e63c8779a9a5000b01'@'1-4c6114c65e295552ab1019e2b046b10e' {'foo': 'bar'}>

Update document:

>>> data = db["5fecc0d7fe5acac6b46359b5eec4f3ff"]   
>>> data['billSeconds'] = 191
>>> db.save(data)
(u'5fecc0d7fe5acac6b46359b5eec4f3ff', u'3-6b8a6bb9f2428c510dcacdd5c918d632')

Traversal database

>>> for id in db:
...     print id
...
'e0658cab843b59e63c8779a9a5000b01'

Delete the document and clean up the database

>>> db.delete(doc)
>>> couch.delete('test')


Related articles: