davidism · GitHub

This adds the ability to fully customize the JSON implementation used by a Flask application. Using a different JSON implementation can greatly speed up API applications that need to work with JSON in most requests.

app.json is an instance of Flask.json_provider_class. flask.json.provider.JSONProvider is the base class that defines dumps, dump, loads, load, and response methods, of which only dumps and loads need to be implemented. For example, here's a provider for orjson:

from flask.json.provider import JSONProvider
import orjson
class OrJSONProvider(JSONProvider):
    def dumps(self, obj, *, option=None, **kwargs):
        if option is None:
            option = orjson.OPT_APPEND_NEWLINE | orjson.OPT_NAIVE_UTC
        return orjson.dumps(obj, option=option).decode()
    def loads(self, s, **kwargs):
        return orjson.loads(s)
# assign to an app instance
app.json = OrJSONProvider(app)
# or assign in a subclass
class MyFlask(Flask):
    json_provider_class = OrJSONProvider
app = MyFlask(__name__)

The methods in flask.json call the methods on app.json if an app context is active, or fall back to the json library. jsonify calls app.json.response. The |tojson filter uses app.json.dumps. Request.json uses app.json.loads and Response.json uses app.json.dumps; the test client uses these as well.

Customizing json_encoder or json_decoder on an app or blueprint, and the JSONEncoder and JSONDecoder classes, are deprecated. This was not an effective way to use other libraries. Customizing per blueprint was requested by an API extension that is no longer maintained and didn't appear to use the feature. It's not clear how it would work with the new provider interface and added overhead to every request. Instead, API frameworks should be using a dedicated object serialization library, then taking advantage of a fast JSON serializer at the application level.

The DefaultJSONProvider is the existing implementation using the built-in json library. The app.config keys JSON_AS_ASCII, JSON_SORT_KEYS, JSONIFY_MIMETYPE, and JSONIFY_PRETTYPRINT_REGULAR are deprecated and have moved to attributes on the default provider. Other providers are not required to support these options.

Read the original on github.com ↗