Skip to content

Instantly share code, notes, and snippets.

@tresbailey
Created October 10, 2013 21:40
Show Gist options
  • Save tresbailey/6926072 to your computer and use it in GitHub Desktop.
Save tresbailey/6926072 to your computer and use it in GitHub Desktop.
Default functions and methods to use with json.dumps for returning valid, full JSON representations of your domain models.
from mongoalchemy.document import Value
from pymongo.objectid import ObjectId
from market import DB
def remove_OIDs(obj, recursive=False):
"""
Removes the ObjectID types from an object
before returning
"""
if isinstance(obj, list):
return [remove_OIDs(ob) for ob in obj]
elif isinstance(obj, AppModel):
response = obj.clean4_dump()
return response
def json_clean(field_value):
"""
Removes the ObjectID types from an object
before returning
"""
if isinstance(field_value,
ObjectId):
return str(field_value)
elif isinstance( field_value,
Value):
return field_value.value
elif isinstance( field_value, list) or isinstance( field_value, tuple):
return [ json_clean(value) for value in field_value ]
elif isinstance( field_value,
dict):
return dict( [ (str(key), json_clean(value)) for key, value in field_value.items() ])
return field_value
class AppModel(DB.Document):
_self_link = DB.StringField(required=False)
_parent_link = DB.StringField(required=False)
filter_fields = tuple()
@classmethod
def has_key(cls, key):
return hasattr(cls, key)
@classmethod
def get(cls, key, default=None):
return getattr(cls, key) or default
def filter_out_fields(self, remove_keys):
return dict([(key_, getattr(self, key_))
for key_ in self.get_fields().iterkeys()
if key_ not in remove_keys and hasattr(self, key_)
])
def clean4_dump(self):
"""
Removes the ObjectID types from an object
before returning
"""
response = dict(self._values)
for field in self._fields:
try:
field_value = self.__getattribute__(field)
if field == 'mongo_id': field = 'id'
response[field] = field_value
response[field] = json_clean(field_value)
except AttributeError:
continue
response = dict([(key, value) for key, value in response.items() if key not in [field._name for field in self.filter_fields]])
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment