Created
May 8, 2018 11:02
-
-
Save vcancy/c69807db353f141809211ead2d538634 to your computer and use it in GitHub Desktop.
Alchemy object json Encoder
This file contains 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
import json | |
from datetime import datetime | |
from sqlalchemy.ext.declarative import DeclarativeMeta | |
class AlchemyEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj.__class__, DeclarativeMeta): | |
# an SQLAlchemy class | |
fields = {} | |
for field in [c.key for c in inspect(obj).mapper.column_attrs]: | |
data = obj.__getattribute__(field) | |
try: | |
if isinstance(data, datetime): | |
data = data.strftime('%Y-%m-%d %H:%M:%S') | |
json.dumps(data) # this will fail on non-encodable values, like other classes | |
fields[field] = data | |
except TypeError: | |
fields[field] = None | |
# a json-encodable dict | |
return fields | |
return json.JSONEncoder.default(self, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment