Created
July 23, 2015 13:35
-
-
Save Tjorriemorrie/81adbbf1dbd3fe4e63b6 to your computer and use it in GitHub Desktop.
Flask-SqlAlchemy encoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# refer http://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json#answer-31569287 | |
from sqlalchemy.ext.declarative import DeclarativeMeta | |
from flask import json | |
class AlchemyEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o.__class__, DeclarativeMeta): | |
data = {} | |
fields = o.__json__() if hasattr(o, '__json__') else dir(o) | |
for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]: | |
value = o.__getattribute__(field) | |
try: | |
json.dumps(value) | |
data[field] = value | |
except TypeError: | |
data[field] = None | |
return data | |
return json.JSONEncoder.default(self, o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment