Created
April 8, 2014 21:27
-
-
Save cbednarski/10195279 to your computer and use it in GitHub Desktop.
Lightweight MongoDB abstraction around python classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MongoDoc(object): | |
connection = None | |
__fields__ = {} | |
__required__ = [] | |
__optional__ = [] | |
__meta__ = ['_id', 'updated'] | |
def set_data(self, data): | |
''' | |
You can set individual fields like this: | |
obj.field1 = 'value' | |
obj.field2 = 'value' | |
Or you can do obj.set_data({"field1":"value", "field2":"value"}) | |
to set many at once | |
''' | |
if data: | |
for name, value in data.iteritems(): | |
self.__dict__[name] = value | |
def save(self): | |
# Verify all required fields are present | |
for req in self.__required__: | |
if req not in self.__dict__: | |
raise ValueError("A required field `%s` is missing" % req) | |
# Disallow fields that aren't required OR optional | |
allowed = self.__required__ + self.__optional__ + self.__meta__ | |
for field in self.__dict__: | |
if field not in allowed: | |
raise ValueError("The field `%s` is not allowed in this object" % field) | |
self.updated = datetime.datetime.utcnow() | |
self.connection[self.__name__].save(self.__dict__) | |
@staticmethod | |
def to_dict(cursor, next_page=None): | |
payload = {"data": []} | |
for record in cursor: | |
record['_id'] = str(record['_id']) | |
payload['data'].append(record) | |
return payload | |
class Person(MongoDoc): | |
__name__ = 'person' | |
__required__ = ['first_name', 'last_name'] | |
__optional__ = ['email', 'phone_numbers'] | |
class Team(MongoDoc): | |
__name__ = 'team' | |
__required__ = ['name', 'members'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment