Skip to content

Instantly share code, notes, and snippets.

@rozza
Created November 17, 2011 09:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rozza/1372780 to your computer and use it in GitHub Desktop.
Save rozza/1372780 to your computer and use it in GitHub Desktop.
Encoder for MongoEngine Object
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)
@iapain
Copy link

iapain commented Nov 17, 2011

MongoEngineCompatibleSerializer shouldn't it be call MongoEngineSerializer :)

@rozza
Copy link
Author

rozza commented Nov 17, 2011

:D

@wpjunior
Copy link

:-)

@ozexpert
Copy link

how can i use this? can you provide me an example?

@rozza
Copy link
Author

rozza commented Jan 19, 2012

Should just be: MongoEngineSerializer().dumps(MongoObject)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment