From 879bf08d18e0e0cedebd0ba950f2ec191a7c2c81 Mon Sep 17 00:00:00 2001 From: Rached Ben Mustapha Date: Mon, 8 Mar 2010 16:42:23 +0100 Subject: [PATCH] Simple implementation of BinaryField --- mongoengine/fields.py | 16 +++++++++++++++- tests/fields.py | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/mongoengine/fields.py b/mongoengine/fields.py index 0793f44b..29c86660 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -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) diff --git a/tests/fields.py b/tests/fields.py index 94f65186..80994b13 100644 --- a/tests/fields.py +++ b/tests/fields.py @@ -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()