Hello,
I'm a beginner in couchdb and couchdb-python.
And I'm not so experienced in Python...
nor in English.
I've played with couchdb for two week-ends, and I'm able now to
do few things, starting from a script I found on the ternet (see
attachment).
I've also added a "login" function to couchdb-python V.05
"Server" class -- I can post a patch if s.o. is interrested
(about 10 lines...) -- to be able to connect ([admins] is set
on my couchdb server).
Howether, I was not able to find a FAQ or an extensive code snippet.
So, I can't figure out some things:
* how to set arbitrary properties on whatever(Document) from
a dict (properly Json encoded, obviously: set up
self.__dict__['_data'][key] = val is not the good way)
* how to retrieve arbitrary key/values _to_python encoded
while the step above will be done
Thanks anyway for your replies,
T. Harding
#!/usr/bin/env python
import couchdb
import couchdb.client as cli
from couchdb.client import Server
from couchdb.schema import View, Document, TextField, IntegerField, DateTimeField
import datetime
import time
import sys
from string import Template
print '*' * 80
print 'begin'
print '*' * 80
# the couchdb server we're talking to
#server = Server('http://127.0.0.1:5984/')
server = couchdb.client.Server('http://127.0.0.1:5984/')
server.login('tom','verysecret')
print 'established database connection'
# create a database, if it already exists, delete and recreate it
try:
db = server.create('animals')
print 'database created'
except:
del server['animals']
db = server.create('animals')
print 'database deleted and created'
print '*' * 80
# create a document class
class Animal(Document):
name = TextField()
age = IntegerField()
genre = TextField()
added = DateTimeField(default=datetime.datetime.now())
def __setitem__(self, key, val):
if (key == 'name'):
self.name = val
elif (key == 'age'):
self.age = val
elif (key == 'genre'):
self.genre = val
elif (key == 'added'):
self.added = val
else:
self.foo = val
class Animals(object):
db = 'Animals'
name = TextField()
age = IntegerField()
genre = TextField()
added = DateTimeField(default=datetime.datetime.now())
reduce = '''
def compute_qty_by_genre(keys,vals):
docs = {'male':0,'female':0,'None':0}
file = open('/tmp/test','a')
file.write(str(vals))
for key in vals:
if key is not None:
docs[key] += 1
else:
docs['None'] += 1
return docs
'''
map = '''
def out_genres(doc):
yield None, doc["genre"]
'''
summary = View('animals_summary',map,reduce,language='python')
map = '''
def show_animals_by_genre(doc):
yield doc['genre'], doc
'''
by_genre = View('animals_by_genre',map,language='python')
map = '''
def show_animal(doc):
yield doc['name'], doc
'''
by_name = View('animal_by_name',map,language='python')
# our input data
animals = [
{'name': 'keiko', 'age': 5, 'genre': 'male','foo':'bar'},
{'name': 'goose', 'age': 11,'baz':5},
{'name': 'joo', 'genre':'female'},
{'name': 'jal', 'genre':'female'},
{'name': 'jo', 'genre':'female'}
]
# store the data in the database
for each in animals:
print each
animal = Animal()
for key,val in each.iteritems():
print key, val
animal[key] = val
print animal
animal.store(db)
print 'animals stored in database'
print '*' * 80
# read the data from the database
print 'reading all animals from database'
print len(db), 'animals retrieved from database'
print 'name', 'age', 'added', 'genre'
for uuid in db:
animal = Animal.load(db, uuid)
name = "name: " + str(animal.name).ljust(15)
age = ", age: " + str(animal.age).rjust(4)
genre = ", genre: " + str(animal.genre).rjust(7)
added = ", added: " + str(animal.added)
print name, age, genre, added
print '*' * 80
def outgenres(the_genres):
for result in db.query(Animals.summary.map_fun,Animals.summary.reduce_fun,language='python',reduce=True):
print '*' * 30
print '* summary by genre'
for genre, qty in result['value'].iteritems():
print "Genre %s: %d animals"%(genre, qty)
print '*' * 30
for genre in the_genres:
print '*' * 80
print 'genre: ', genre
if genre == '':
genre = None
#else:
# genre = "'%s'"%genre
print '*' * 80
print '* Animals in: ', genre
print '*' * 30
for row in db.query(Animals.by_genre.map_fun,Animals.by_genre.reduce_fun,language='python',key=genre):
for key, val in row.value.iteritems():
print '%s:\t%s'%(key, str(val))
print '*' *50
def outanimals(animals):
print '*' * 80
print "* Querying animals"
print '*' * 80
for animal in animals:
print '*' * 80
print 'querying for animal: ', animal
print '*' * 30
if animal == '':
animal = None
for row in db.query(Animals.by_name.map_fun,Animals.by_name.reduce_fun,language='python',key=animal):
print '* Found Animal: ', row.key
print '*' * 30
for key, val in row.value.iteritems():
print '%s:\t%s'%(key, str(val))
print '*' *50
print '*' * 80
print
print
print
# query the database
print 'querying the database'
print 'What genres? (comma separated)'
genres=sys.stdin.readline()
genres = genres.strip()
genres=genres.split(',')
outgenres(genres)
print 'querying the database'
print 'Which animals do you want to display? (comma separated)'
animals =sys.stdin.readline().strip()
animals=animals.split(',')
outanimals(animals)