Skip to content

Instantly share code, notes, and snippets.

@stavinsky
Last active August 29, 2015 14:07
Show Gist options
  • Save stavinsky/cddf4f068467b8744fe6 to your computer and use it in GitHub Desktop.
Save stavinsky/cddf4f068467b8744fe6 to your computer and use it in GitHub Desktop.
sqlalchemy load data from json and export to json
##this is my way to import and export data to json
## actually not json, but dict. But you can convert json to dict very simple way:
## https://docs.python.org/2/library/json.html
class BaseExtend(object):
def to_dict(self):
d = dict()
for c in self.__table__.columns:
if isinstance(getattr(self, c.name), datetime):
d[c.name] = str(getattr(self, c.name)).split('.')[0]
else:
d[c.name] = getattr(self, c.name)
return d
def from_dict(self, d, filter=('created', 'updated')):
for c in self.__table__.columns:
if c.name not in filter and d.get(c.name):
setattr(self, c.name, d[c.name])
return True
Base = declarative_base(cls=BaseExtend)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment