Skip to content

Instantly share code, notes, and snippets.

@georgefs
Created April 19, 2013 23:25
Show Gist options
  • Save georgefs/5423934 to your computer and use it in GitHub Desktop.
Save georgefs/5423934 to your computer and use it in GitHub Desktop.
cover mongoengine document to raw dict
from bson.objectid import ObjectId
from bson.dbref import DBRef
from mongoengine.document import Document
import collections
from datetime import datetime
from mongoengine.queryset import QuerySet
def raw_data(data):
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, str):
return data
elif isinstance(data, QuerySet):
return raw_data([i for i in data])
elif isinstance(data, datetime):
return data.strftime('%s000')
elif isinstance(data, ObjectId):
return str(data)
elif isinstance(data, Document):
data.select_related()
return raw_data(data.__dict__.get('_data'))
elif isinstance(data, collections.Mapping):
return dict(map(raw_data, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(raw_data, data))
else:
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment