Created
February 8, 2020 20:43
-
-
Save frfernandezdev/f86c7b5a8f4154a5a454347d630be510 to your computer and use it in GitHub Desktop.
Serialize Flask-SQLAlchemy Models into JSON
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
from flask import Flask, jsonify | |
from json_serializable import JSONSerializable | |
from flask_sqlalchemy import SQLAlchemy | |
# Initialize database instance. | |
db = SQLAlchemy() | |
# Create app flask | |
app = Flask(__name__) | |
JSONSerializable(app) | |
# Connected app context with database | |
with app.app_context(): | |
db.init_app(app) | |
db.create_all() | |
class User(db.Model): | |
__tablename__ = 'users' | |
uid = Column(String(), primary_key=True) | |
email = Column(String(), nullable=True, unique=True) | |
displayName = Column(String(), nullable=True, unique=True) | |
name = Column(String(), nullable=True) | |
def __init__(self, | |
uid : str, | |
email : str, | |
displayName : str, | |
name : str, | |
): | |
self.uid = id | |
self.email = email | |
self.displayName = displayName | |
self.name = name | |
@app.route('/json') | |
def simple_json(): | |
return jsonify(User.query.all()) | |
@app.route('/dict') | |
def simple_dict(): | |
return jsonify(ok=True, args=[]) |
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 | |
import flask | |
from collections import OrderedDict | |
from datetime import datetime | |
try: | |
from flask_sqlalchemy.model import Model | |
except ImportError as e: | |
print(str(e)) | |
class JSONEncoder(json.JSONEncoder): | |
def default(self, o): | |
def recursive(p): | |
result = OrderedDict() | |
for k in p.keys(): | |
result[k] = getattr(o, k) | |
if isinstance(result[k], dict): | |
result[k] = recursive(result[k]) | |
if isinstance(result[k], datetime): | |
result[k] = result[k].timestamp() | |
return result | |
if isinstance(o, Model): | |
return dict(recursive(o.__mapper__.c)) | |
return flask.json.JSONEncoder.default(self, o) | |
def JSONSerializable(app=None, **kwargs): | |
if app is not None: | |
app.json_encoder = JSONEncoder | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment