Skip to content

Instantly share code, notes, and snippets.

@madsmtm
Created March 26, 2019 09:01
Show Gist options
  • Save madsmtm/f9dce859c09bfd83a9395b56d61df082 to your computer and use it in GitHub Desktop.
Save madsmtm/f9dce859c09bfd83a9395b56d61df082 to your computer and use it in GitHub Desktop.
Automatic JSON serialization for Flask
# Credit to:
# - http://derrickgilland.com/posts/automatic-json-serialization-in-flask-views/
# - https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class
from flask import Response, Flask, jsonify
class AutoJSON(Response):
@classmethod
def force_type(cls, response, environ=None):
"""Override to convert list & dict returns to json."""
if isinstance(response, (list, dict)):
response = jsonify(response)
return super(Response, cls).force_type(response, environ)
class CustomFlask(Flask):
"""Override Flask default response class."""
response_cls = AutoJSON
app = CustomFlask(__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment