Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created April 24, 2012 19:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/2483160 to your computer and use it in GitHub Desktop.
Save nikoheikkila/2483160 to your computer and use it in GitHub Desktop.
Python: CouchDB example
"""
cdb_example.py
CouchDB example script
API documentation: http://packages.python.org/CouchDB/getting-started.html
"""
import sys
import couchdb
def couchdb_connect(username, password, host="127.0.0.1", session=None):
"""
Connect to CouchDB server and return an instance object
of the database connection or 'False' on error.
"""
try:
# Connect and send credentials.
server = couchdb.Server(host)
server.resource.credentials = (username, password)
return server
except Exception, e:
print "Fatal error: %s" % str(e)
return False
def main(argv=None):
if argv is None:
argv = sys.argv
if argv[:1] in ['h', 'help']:
print "This is a help text, someone write it, please."
return 1
connection = couchdb_connect("admin", "secret")
if not connection:
print "Error connecting to server, exiting."
return 2
else:
# Select database 'test'.
db = connection['test']
# Construct data to send.
document = {
'name' : "J. James",
'age' : 75,
'gender': "Male",
'height': 175,
'weight': 68,
}
# Fetch document ID and revision.
doc_id, doc_rev = db.save(document)
# Fetch row with given id (=primary key)
row = db[doc_id]
# Print it out
for key in row:
print "%s: %s" % (key, row[key])
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment