Created
March 26, 2019 09:01
-
-
Save madsmtm/f9dce859c09bfd83a9395b56d61df082 to your computer and use it in GitHub Desktop.
Automatic JSON serialization for Flask
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
# 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