Skip to content

Instantly share code, notes, and snippets.

@adamgoucher
Created June 10, 2013 16:08
Show Gist options
  • Save adamgoucher/5749984 to your computer and use it in GitHub Desktop.
Save adamgoucher/5749984 to your computer and use it in GitHub Desktop.
An example of using CouchDB within Py.Saunter ... including both parts of the setup since its not actually in Py.Saunter at the moment, but will in the future.
import ConfigParser
import couchdb.client
import random
import socket
# this will be in py.saunter
class ProviderException(Exception): pass
# as will this
class CouchProvider(object):
def __init__(self, database):
# read url from the config
if config.has_section('couchdb') and config.has_option('couchdb', 'url'):
url = config.get('couchdb', 'url')
else:
url = None
# make sure we can connect to the server
server = couchdb.client.Server(url=url)
try:
server.version()
except socket.error:
raise ProviderException('couch server not found at %s' % url)
# check that the database is in the server
if database not in server:
raise ProviderException('database "%s" does not exist' % database)
self.database = server[database]
# this will live per-project in $saunter_root/lib/providers
class MySubclassedCouchProvider(CouchProvider):
def __init__(self, database):
super(MySubclassedCouchProvider, self).__init__(database)
def random_user(self):
map_fun = '''function(doc) {
emit(doc.username, null);
}'''
all_users = [user.id for user in self.database.query(map_fun=map_fun)]
random_user_id = random.choice(all_users)
return self.database.get(random_user_id)
def random_admin_user(self):
map_fun = '''function(doc) {
if (doc.role == 'admin')
emit(doc.username, null);
}'''
all_users = [user.id for user in self.database.query(map_fun=map_fun)]
random_user_id = random.choice(all_users)
return self.database.get(random_user_id)
if __name__ == '__main__':
# in a py.saunter context, this is stored in the config
config = ConfigParser.ConfigParser()
config.add_section('couchdb')
config.set('couchdb', 'url', 'http://localhost:5984/')
c = MySubclassedCouchProvider('people')
# records from couchdb are 'just' dictionaries
random_user = c.random_user()
print(random_user['username'])
random_admin_user = c.random_admin_user()
print(random_admin_user['username'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment