Created
November 17, 2011 09:28
-
-
Save rozza/1372780 to your computer and use it in GitHub Desktop.
Encoder for MongoEngine Object
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
import datetime | |
import simplejson | |
from pymongo.dbref import DBRef | |
from pymongo.objectid import ObjectId | |
class MongoEngineEncoder(simplejson.JSONEncoder): | |
"""Handles Encoding of ObjectId's""" | |
def default(self, obj, **kwargs): | |
if isinstance(obj, datetime.datetime): | |
return obj.strftime('%Y-%m-%dT%H:%M:%S') | |
elif isinstance(obj, datetime.date): | |
return obj.strftime('%Y-%m-%d') | |
elif isinstance(obj, ObjectId): | |
return str(obj) | |
elif isinstance(obj, DBRef): | |
return {'collection': obj.collection, | |
'id': str(obj.id), | |
'database': obj.database} | |
return simplejson.JSONEncoder.default(obj, **kwargs) | |
class MongoEngineSerializer(object): | |
"""Wrapper around simplejson that strips whitespace and uses | |
MongoEngineEncoder to handle dumping datetimes / ObjectId's and DBRefs | |
""" | |
def loads(self, payload): | |
return simplejson.loads(payload) | |
def dumps(self, obj, cls=None): | |
cls = cls or MongoEngineEncoder | |
return simplejson.dumps(obj.to_mongo(), separators=(',', ':'), cls=cls) |
:D
:-)
how can i use this? can you provide me an example?
Should just be: MongoEngineSerializer().dumps(MongoObject)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MongoEngineCompatibleSerializer
shouldn't it be callMongoEngineSerializer
:)