radpotato
radpotato

Reputation: 1412

query cloudant with python

There may be an obvious answer to this, but I can't seem to find it anywhere: what's the best way to query couchdb databases stored on cloudant servers? I try using temporary views, a la the couchdb.py instructions:

>>> db['johndoe'] = dict(type='Person', name='John Doe')
>>> db['maryjane'] = dict(type='Person', name='Mary Jane')
>>> db['gotham'] = dict(type='City', name='Gotham City')
>>> map_fun = '''function(doc) {
...     if (doc.type == 'Person')
...         emit(doc.name, null);
... }'''
>>> for row in db.query(map_fun):
...     print row.key
John Doe
Mary Jane

While this works on locally hosted databases, with CloudAnt it returns the error:

couchdb.http.ServerError: (403, ('forbidden', 'temp views are disabled on Cloudant'))

I've read the cloudant tutorial on querying but the querying syntax proposed seems clumsy and it's not obvious how to work it into python! Is there an easy way around this?

Upvotes: 4

Views: 2801

Answers (4)

Mike Rhodes
Mike Rhodes

Reputation: 1836

Just noting that Cloudant now has an official python library, https://github.com/cloudant/python-cloudant.

Upvotes: 1

Simon Fearby
Simon Fearby

Reputation: 187

This is how I am adding a record with python.

import requests
import json

doc = {
  'username':'kerrie',
  'high_score':550,
  'level':3
}

auth = ('username', 'password')
headers = {'Content-type': 'application/json'}

post_url = "https://account.cloudant.com/database/kerrie".format(auth[0])

r = requests.put(post_url,  auth=auth,  headers=headers,  data=json.dumps(doc))
print json.dumps(r.json(), indent=1)

This is how i query 10 records in Python.

import requests
import json
auth = ('username', 'password')
get_url = "https://account.cloudant.com/database/_all_docs?limit=10".format(auth[0])
r = requests.get(get_url, auth=auth)
print json.dumps(r.json(), indent=1)

Upvotes: 3

mrbillyocean
mrbillyocean

Reputation: 1391

You should probably use couchdbkit. It makes setting up views easy. I don't think you can use temporary views in Cloudant anymore.

Upvotes: 0

Ryan Ramage
Ryan Ramage

Reputation: 2616

The reason Cloudant forbids temp views is because they do not scale. You will need to create a design document with defined views in it. Here is a link to what a design document is like with views defined on it:

http://max.ic.ht/_utils/document.html?action/_design/action

I am not sure about how to do it in couchdb.py, but you might want to try a different python library. Here is a link to the section about creating views in couchquery

http://mikeal.github.com/couchquery/#creating-views

Upvotes: 1

Related Questions