Simple implementation of BinaryField

This commit is contained in:
Rached Ben Mustapha 2010-03-08 16:42:23 +01:00
parent 53c0cdc0c1
commit 879bf08d18
2 changed files with 33 additions and 1 deletions

View File

@ -11,7 +11,8 @@ import decimal
__all__ = ['StringField', 'IntField', 'FloatField', 'BooleanField',
'DateTimeField', 'EmbeddedDocumentField', 'ListField', 'DictField',
'ObjectIdField', 'ReferenceField', 'ValidationError',
'DecimalField', 'URLField', 'GenericReferenceField']
'DecimalField', 'URLField', 'GenericReferenceField',
'BinaryField']
RECURSIVE_REFERENCE_CONSTANT = 'self'
@ -442,3 +443,16 @@ class GenericReferenceField(BaseField):
def prepare_query_value(self, op, value):
return self.to_mongo(value)['_ref']
class BinaryField(BaseField):
"""A binary data field.
"""
def __init__(self, **kwargs):
super(BinaryField, self).__init__(**kwargs)
def to_mongo(self, value):
return pymongo.binary.Binary(value)
def to_python(self, value):
return str(value)

View File

@ -495,6 +495,24 @@ class FieldTest(unittest.TestCase):
Post.drop_collection()
User.drop_collection()
def test_binary_fields(self):
"""Ensure that binary fields can be stored and retrieved.
"""
class Attachment(Document):
content_type = StringField()
blob = BinaryField()
BLOB = '\xe6\x00\xc4\xff\x07'
MIME_TYPE = 'application/octet-stream'
Attachment.drop_collection()
attachment = Attachment(content_type=MIME_TYPE, blob=BLOB)
attachment.save()
attachment_1 = Attachment.objects().first()
self.assertEqual(MIME_TYPE, attachment_1.content_type)
self.assertEqual(BLOB, attachment_1.blob)
if __name__ == '__main__':
unittest.main()