0

the "how to serialize a sqlalchemy model" has many solutions. many of which change as parts and pieces get changed by flask.

jsonify a SQLAlchemy result set in Flask

i've settled on using py-flask-jsontools. made a copy of the repository and integrated several fixes from various forks. the orginal author seems mia.

https://github.com/slippers/py-flask-jsontools

here is the test for sqlalchemy i made to explore serializing to json with and without flask context.

https://github.com/slippers/py-flask-jsontools/blob/master/tests/sqlalchemy-test.py

? how do I serialize sqlalchemy model to json without calling

json.dumps( "some query object", cls=DynamicJSONEncoder)

especially when there is request context and flask knows what serializer class to use.

Community
  • 1
  • 1
user2647293
  • 25
  • 1
  • 7

1 Answers1

0

extend the JsonResponse to call dumps with the DynamicJSONEncoder. JsonResponse has optional params for different http response codes and headers.

class SqlAlchemyResponse(JsonResponse):
    def preprocess_response_data(self, response):
        return json.dumps(response, cls=DynamicJSONEncoder)

@app.route('/person', methods=['GET']) 
def list_persons():
    rs = self.session.query(Person).all()
    return SqlAlchemyResponse(rs)
user2647293
  • 25
  • 1
  • 7