Using Python with Cloudant

By Max Thayer

For more guides like this, check out our documentation.

Python's readability and standardized coding practices make it effortless to read and write, and as a result it's great for teaching. Academicians and scientists make heavy use of it for all manner of research and analysis, notably the Natural Language ToolKit, SciPy, NumPy, Matplotlib, Numba, and PyTables. Python was the first language I felt comfortable with, and to be honest, I owe my coding career to the Boston Python community. Thanks, gang :D

Python is also superb for working with Cloudant. If you don't already have Python, oh golly, go get it.

Packages: pip and virtualenv

The Python community uses a package manager called "pip" to install, uninstall, and upload packages to an online repository called PyPI. If you don't have pip, get pip

Then, you can install packages as easy as this:

pip install [name]

That'll install to someplace on your PYTHONPATH, so your projects have access to the downloaded package. If you want to isolate dependencies between projects, use virtualenv, which you can install like this:

sudo pip install virtualenv

Then, to create an isolated Python environment for your project, just do this:

# create a `venv` folder
virtualenv venv
# use its `bin`, etc., folders for Python business
source venv/bin/activate

You should see (venv) prepended to your terminal's command line. Now, any pip packages you install will go into that venv folder.

For even more convenience creating virtual environments for your Python projects, check out virtualenvwrapper, which extends virtualenv for more ease-of-use.

Libraries: CouchDB-Python, Couchdbkit, and Requests

Because Cloudant's API so resembles that of CouchDB's, you can use CouchDB client libraries like CouchDB-Python and Couchdbkit to work with Cloudant. Or, you can consume Cloudant's HTTP API directly using an HTTP library like Requests.

CouchDB-Python

Cloudant's API resembles the way Python dict objects work, which makes CouchDB-Python wickedly intuitive to use. To get the library, just pip it!

pip install couchdb

Using CouchDB-Python is wicked easy. Check it out:

# connecting to your Cloudant instance
import couchdb
couch = couchdb.Server("https://%s.cloudant.com" % USERNAME)
couch.resource.credentials = (USERNAME, PASSWORD)

# accessing a database
db = couch['test']
# or, creating one
db = couch.create('test')

# accessing a document
doc = db[DOCUMENT_ID]
# or, creating one
doc_id, doc_rev = db.save({
  'name': 'Mike Broberg',
  'title': 'Fun Captain',
  'superpower': 'More fun than a hallucinogenic trampoline'
})
doc = db[doc_id]

Query results are treated as iterators, like this:

# print all docs in the database
for doc in db:
  print doc
# or, do the same on a pre-defined index
# where 'DDOC/INDEX' maps to '_design/DDOC/_view/INDEX'
# in the HTTP API
for doc in db.view('DDOC/INDEX'):
  print doc

Check out the documentation for even more goodies :D

Couchdbkit

Just like CouchDB-Python, Couchdbkit uses native Python objects to make interacting with Cloudant effortless, but it provides a fuller API and more convenience methods. To install it, just pip it!

pip install couchdbkit

Its interface is very similar, too, which you can see in more detail here:

import couchdbkit

# connect to cloudant
server = couchdbkit.Server('https://USERNAME:PASSWORD@USERNAME.cloudant.com')
db = server.get_or_create_db('posts')

# save a document
db.save_doc({
    'author': 'Mike Broberg',
    'content': "In my younger and more vulnerable years, my father told me, 'Son, turn that racket down.'"
})

# save lots of docs :D
docs = [{...}, {...}, {...}]
db.bulk_save(docs)

Couchdbkit exposes a document class for adding simple schemas to your application, like so:

class Post(couchdbkit.Document):
  author = couchdbkit.StringProperty()
  content = couchdbkit.StringProperty()

# associate posts with a given database object
Post.set_db(db)
new_post = Post(
  author="Mike Broberg",
  content="In his spare time, Mike Broberg enjoys barbecuing meats of various origins."
)

# save the post to its associated database
new_post.save()

Performing queries returns iterators:

# print all docs in the database
for doc in db.view('_all_docs'):
  print doc

# or, do the same on a pre-defined index
# where 'DDOC/INDEX' maps to '_design/DDOC/_view/INDEX'
# in the HTTP API
for doc in db.view('DDOC/INDEX'):
  print doc

For more detail than you could ever want, check out the API Documentation.

Requests

Because Cloudant's API is just an HTTP interface, you can interact with it from any HTTP library. Python has a beautiful HTTP library called Requests, so if you don't want to deal with all the abstraction of a client library, use that. Here's how:

First, pip!

pip install requests

Then, let's talk to our database:

import requests

account_url = 'https://USERNAME:PASSWORD@USERNAME.cloudant.com'

response = requests.get(account_url)
print response.status_code
# 200
print response.json()
# {
#     "couchdb": "Welcome",
#     "version": "1.0.2",
#     "cloudant_build": "1678"
# }

Hey, why not write something?

import json

db_url = account_url + '/posts'
doc = dict(
    author='Mike Broberg',
    content="I once did a triple backflip over seventeen buses using only a red Solo cup and a copy of 'Gender Outlaw'."
)
headers = {'Content-type': 'application/json'}
response = requests.post(db_url, data=json.dumps(doc), headers=headers)
print response.status_code
# 201

Dandy, eh? Just hit Cloudant's API by URL directly. Don't forget to set headers and request bodies appropriately! See Requests' documentation for more info.

Frameworks: Flask and Django

Python is great for web development. Two frameworks stand out in the community for building robust web applications, Flask and Django:

Flask

Flask is a micro-framework that makes it effortless to rapidly develop web apps. To get it, run pip install flask. Then, check out the example code:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Run it with python [file] and boom, you're live. That's all it takes to build a website with Flask.

A rich community of addons, plugins, and integrations mean you can add features and functionality quickly without relying on monolithic software choices. Just google "flask [thing]" and you'll more than probably find integrations that suit your needs.

Django

Django is to Python as Ruby on Rails is to Ruby: an enormous, web-focused project that attempts to make intelligent design decisions about app structure, architecture, layout, and tooling so that you can focus on building your app. Some of what it provides out of the box:

  • A SQL model layer

  • HTML templating

  • Automatic administrative interface

  • Elegant URL routing

  • Internationalization support

  • Authentication and authorization systems

Django has an enormous community of addons, plugins, integrations, and the like, so if you need more, just google "django [thing]" and you'll likely find what you need. To get started with Django, check out their documentation.

CouchApps

The original CouchApp utility, couchapp, is written in Python. Though the original author has chosen to focus on Erica instead, the python utility is still more feature-complete and works just fine. To install the utility, just pip it:

sudo pip install couchapp

Then, you can scaffold, push, and even pull CouchApps right from the command line:

# scaffold a couchapp
couchapp generate cloudant
# push it live
couchapp push cloudant https://USERNAME:PASSWORD@USERNAME.cloudant.com/DATABASE
# clone it!
couchapp clone https://USERNAME:PASSWORD@USERNAME.cloudant.com/DATABASE/_design/cloudant cloudant2
# oh look, there it is!
ls cloudant2

The python utility also supports the _docs folder, which couchapp will upload to your target database as JSON documents rather than attachments. Very nifty for scaffolding data, or syncing projects.


As always, if you have any trouble, check our docs, post your question to StackOverflow, ping us on IRC, or if you'd like to discuss the matter in private, email us at support@cloudant.com.

Happy coding!

Create an account and try it yourself

Sign Up for Updates!

Recent Posts