Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Created January 30, 2013 16:41
Show Gist options
  • Save iolloyd/4674527 to your computer and use it in GitHub Desktop.
Save iolloyd/4674527 to your computer and use it in GitHub Desktop.
Non-circular recursive json printer. It's naive since I am sure there are more type cases that it can't handle but it's good enough for the most cases and trivial to extend.
class ModelBase(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
def get_fields(self, view):
"""Retrieves the fields list defined for the specified view.
"""
if view == 'list_view':
fields = self.list_view
elif view == 'single_view':
fields = self.single_view
else:
fields = self.__mapper__.columns
return fields
def to_json(self, view='list_view', this_class=None):
out = {}
for f in self.get_fields(view):
obj = getattr(self, f)
if hasattr(obj, 'to_json'):
if not this_class == self.__class__:
out[f] = obj.to_json(view=view, this_class=this_class)
elif hasattr(obj, 'isoformat'):
out[f] = obj.isoformat()
elif isinstance(obj, datetime.timedelta):
out[f] = (datetime.datetime.min + obj).time().isoformat()
elif isinstance(obj, (basestring, int, long, )):
out[f] = obj
elif obj is None:
out[f] = obj
return dict(out)
Base = declarative_base(cls=ModelBase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment