Skip to content

Instantly share code, notes, and snippets.

@chopachom
Created December 7, 2012 22:14
Show Gist options
  • Save chopachom/4236945 to your computer and use it in GitHub Desktop.
Save chopachom/4236945 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import types
from mongoengine import EmbeddedDocument, EmbeddedDocumentField, ListField
class Resource(object):
#: :type Document: :class:`mongoengine.Document`
Document = None
def __init__(self):
if not self.Document:
raise NameError("You should add a document class to the resource")
def get_query_set(self):
return self.Document.objects
def to_python(self):
queryset = self.get_query_set()
for document in queryset:
yield self.dehydrate_document(document)
def dehydrate_document(self, document):
return {key:self.dehydrate_field(document[key]) for key in document}
# return raw_doc
def dehydrate_field(self, field):
if isinstance(field, EmbeddedDocument):
return self.dehydrate_document(field)
if isinstance(field, types.ListType):
return [self.dehydrate_field(el) for el in field]
return field
def from_python(self, dicts):
if not isinstance(dicts, types.ListType):
dicts = [dicts]
for dict in dicts:
yield self.hydrate_document(self.Document, dict)
def hydrate_document(self, type, raw_dict):
dict = {}
for field in raw_dict:
if field in type._fields:
dict[field] = self.hydrate_field(type._fields[field], raw_dict[field])
return type(**dict)
def hydrate_field(self, type, field):
if field is None:
return None
if isinstance(type, EmbeddedDocumentField):
return self.hydrate_document(type.document_type, field)
if isinstance(type, ListField):
return [self.hydrate_field(type.field, el) for el in field]
return field
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment