You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@couchdb.apache.org by Ian Mulvany <ia...@mulvany.net> on 2008/05/20 20:46:51 UTC
couchdb-python: failing to 'PUT' document views
Hi,
I'd like to use the couchdb python API to insert views, but I am
failing to understand the
difference between a view and a document.
I've installed couchdb on max osx 10.5
I followed the very nice instructions from
http://blog.sweetspot.dm/tech-babble-resting-with-couchdb/
and using the documentation with the provided python api we have:
import httplib, simplejson
def prettyPrint(s):
"""Prettyprints the json response of an HTTPResponse object"""
# HTTPResponse instance -> Python object -> str
print simplejson.dumps(simplejson.loads(s.read()), sort_keys=True, indent=4)
class Couch:
"""Basic wrapper class for operations on a couchDB"""
def __init__(self, host, port=5984, options=None):
self.host = host
self.port = port
def connect(self):
return httplib.HTTPConnection(self.host, self.port) # No close()
def createDb(self, dbName):
"""Creates a new database on the server"""
r = self.put(''.join(['/',dbName,'/']), "")
prettyPrint(r)
def saveDoc(self, dbName, body, docId=None):
"""Save/create a document to/in a given database"""
if docId:
print ''.join(['/', dbName, '/', docId])
r = self.put(''.join(['/', dbName, '/', docId]), body)
else:
r = self.post(''.join(['/', dbName, '/']), body)
prettyPrint(r)
def put(self, uri, body):
c = self.connect()
if len(body) > 0:
headers = {"Content-type": "application/json"}
c.request("PUT", uri, body, headers)
else:
c.request("PUT", uri, body)
return c.getresponse()
# test creation of db and addition of doc
foo = Couch('localhost', '5984')
foo.createDb('testblog')
doc = """
{
"value":
{
"Subject":"I like Planktion",
"Author":"Rusty",
"type":"post",
"PostedDate":"2006-08-15T17:30:12-04:00",
"Tags":["plankton", "baseball", "decisions"],
"Body":"I decided today that I don't like baseball. I like
plankton."
}
}
"""
foo.saveDoc('testblog', doc, 'mypost')
# this works, but now:
view = """
{
"language": "text/javascript", # also breaks when I omit this line
"views":
{
"all": "function(doc) { if (doc.type == 'post') map(null, doc) }",
"by_tags": "function(doc) { if (doc.type == 'post') map(doc.Tags, doc) }"
}
}
"""
foo.saveDoc('testblog', view, '_design/addview2')
# does not work but provides the following error:ValueError: No JSON
object could be decoded
Any advice would be greatly appreciated,
- Ian