from couchdb import schema as from couchdb client import Server import

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from couchdb import schema as s
from couchdb.client import Server
import settings
DB = None
class Manager(object):
def __init__(self, cls):
self.cls = cls
self.type = cls.TYPE
def all(self):
args = {'type': self.type}
mapf = """function(doc) { if (doc.type == '%(type)s') { emit(doc._id, doc); } }""" % args
return DB.query(mapf)
class Model(s.Document):
@classmethod
def objects(cls):
return Manager(cls)
def __init__(self, *args, **kwargs):
super(Model, self).__init__(*args, **kwargs)
if not hasattr(self, 'TYPE'):
raise Exception('Model subclass should provide TYPE class attribute')
def save(self):
self.store(DB)
def connect(db_name, force=False):
global DB
if DB is None or Force:
server = Server('http://localhost:5984/')
try:
DB = server[db_name]
except Exception:
DB = create_db(db_name)
return DB
def create_db(db_name, force=False):
try:
server.create(db_name)
except Exception:
if force:
del server[db_name]
server.create(db_name)
return server[db_name]
connect(settings.DATABASE_NAME)