Skip to content

Instantly share code, notes, and snippets.

@tylerharper
Forked from leah/CouchObject.py
Created February 23, 2010 11:37
Show Gist options
  • Save tylerharper/312089 to your computer and use it in GitHub Desktop.
Save tylerharper/312089 to your computer and use it in GitHub Desktop.
class CouchObject(object):
'''
Convert between a CouchDB document and Python object.
Create Python objects while maintaining a schema-free database.
Define object properties without storing null fields.
'''
@property
def id(self):
return self._id
@property
def rev(self):
return self._rev
def all_fields(self):
# return a list of expected fields
raise NotImplementedError("all_fields must return a list of all fields for %s" % self.__class__)
def __init__(self, **kwargs):
self.server, self.db = get_server_db()
# create object properties for all desired fields
for field_name in self.all_fields():
# check if field exists in document
if field_name in kwargs and kwargs[field_name] is not None:
value = kwargs[field_name]
else:
value = None
setattr(self, field_name, value)
def to_dict(self):
# dictionary from properties
data_dict = {}
for field_name in self.all_fields():
value = getattr(self, field_name)
if value is not None: # don't store null fields!
data_dict[field_name] = value
return data_dict
def save(self):
self.db.update([self.to_dict()])
@staticmethod
def save_batch(docs):
server, db = get_server_db()
db.update([doc.to_dict() for doc in docs])
def delete(self):
del self.db[self._id]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment