Added CollectionManager, made connection module
All connection-related functions are now in connection.py. Created a ConnectionManager class for interacting with a collection in the database. Top-level document classes have an instance of a ConnectionManager (Document.collection). Defined a 'save' method on top-level document's that uses the collection manager's '_save_document' method to save the document to the database. Added tests for CollectionManagers -- all unit tests now require a valid connection to the database, which is set up in the tests' setUp method.
This commit is contained in:
parent
688fd5af66
commit
c99f5c4ec1
9 changed files with 173 additions and 36 deletions
|
|
@ -1,3 +1,4 @@
|
|||
from collection import CollectionManager
|
||||
|
||||
|
||||
class ValidationError(Exception):
|
||||
|
|
@ -128,7 +129,13 @@ class TopLevelDocumentMetaclass(DocumentMetaclass):
|
|||
}
|
||||
meta.update(attrs.get('meta', {}))
|
||||
attrs['_meta'] = meta
|
||||
return super_new(cls, name, bases, attrs)
|
||||
|
||||
# Set up collection manager, needs the class to have fields so use
|
||||
# DocumentMetaclass before instantiating CollectionManager object
|
||||
new_class = super_new(cls, name, bases, attrs)
|
||||
setattr(new_class, 'collection', CollectionManager(new_class))
|
||||
|
||||
return new_class
|
||||
|
||||
|
||||
class BaseDocument(object):
|
||||
|
|
@ -141,7 +148,7 @@ class BaseDocument(object):
|
|||
setattr(self, attr_name, values.pop(attr_name))
|
||||
else:
|
||||
if attr_value.required:
|
||||
raise ValidationError('Field "%s" is required' % self.name)
|
||||
raise ValidationError('Field "%s" is required' % attr_name)
|
||||
# Use default value
|
||||
setattr(self, attr_name, getattr(self, attr_name, None))
|
||||
|
||||
|
|
@ -179,4 +186,9 @@ class BaseDocument(object):
|
|||
def _to_mongo(self):
|
||||
"""Return data dictionary ready for use with MongoDB.
|
||||
"""
|
||||
return dict((k, v) for k, v in self._data.items() if v is not None)
|
||||
data = {}
|
||||
for field_name, field in self._fields.items():
|
||||
value = getattr(self, field_name, None)
|
||||
if value is not None:
|
||||
data[field_name] = field._to_mongo(value)
|
||||
return data
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue