add json provider interface
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent c356c6d · Browse files · 13 files·+662 added−282 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+662 added−282 removed
- tests:+29 added−83 removed
- other:+633 added−199 removed
Provenance
- Commit
69f9845- Tree
70e960f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c356c6d
13 files changed+662 added−282 removed
modified:docs/api.rst+16 added-14 removed
234 unmodified lines235 ------------236 237 .. module:: flask.json238 239-Flask uses the built-in :mod:`json` module for handling JSON. It will240-use the current blueprint's or application's JSON encoder and decoder241-for easier customization. By default it handles some extra data types:239+Flask uses Python's built-in :mod:`json` module for handling JSON by240+default. The JSON implementation can be changed by assigning a different241+provider to :attr:`flask.Flask.json_provider_class` or242+:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will243+use methods on ``app.json`` if an app context is active.244 243-- :class:`datetime.datetime` and :class:`datetime.date` are serialized244- to :rfc:`822` strings. This is the same as the HTTP date format.245-- :class:`uuid.UUID` is serialized to a string.246-- :class:`dataclasses.dataclass` is passed to247- :func:`dataclasses.asdict`.248-- :class:`~markupsafe.Markup` (or any object with a ``__html__``249- method) will call the ``__html__`` method to get a string.245+Jinja's ``|tojson`` filter is configured to use the app's JSON provider.246+The filter marks the output with ``|safe``. Use it to render data inside247+HTML ``<script>`` tags.248 251-Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`252-function. The filter marks the output with ``|safe`` automatically. Use253-the filter to render data inside ``<script>`` tags.254-249 .. sourcecode:: html+jinja250 251 <script>252 const names = {{ names|tosjon }};9 unmodified lines262 .. autofunction:: loads263 264 .. autofunction:: load265 266+.. autoclass:: flask.json.provider.JSONProvider267+ :members:268+ :member-order: bysource269+270+.. autoclass:: flask.json.provider.DefaultJSONProvider271+ :members:272+ :member-order: bysource273+274 .. autoclass:: JSONEncoder275 :members:276 277 .. autoclass:: JSONDecoder474 unmodified linesmodified:docs/config.rst+23 added-2 removed
299 unmodified lines300 templates, and should typically remain enabled.301 302 Default: ``True``303 304+ .. deprecated:: 2.2305+ Will be removed in Flask 2.3. Set ``app.json.ensure_ascii``306+ instead.307+308 .. py:data:: JSON_SORT_KEYS309 310 Sort the keys of JSON objects alphabetically. This is useful for caching311 because it ensures the data is serialized the same way no matter what1 unmodified line313 possible performance improvement at the cost of caching.314 315 Default: ``True``316 317+ .. deprecated:: 2.2318+ Will be removed in Flask 2.3. Set ``app.json.sort_keys``319+ instead.320+321 .. py:data:: JSONIFY_PRETTYPRINT_REGULAR322 315- ``jsonify`` responses will be output with newlines, spaces, and indentation316- for easier reading by humans. Always enabled in debug mode.323+ :func:`~flask.jsonify` responses will be output with newlines,324+ spaces, and indentation for easier reading by humans. Always enabled325+ in debug mode.326 327 Default: ``False``328 329+ .. deprecated:: 2.2330+ Will be removed in Flask 2.3. Set ``app.json.compact`` instead.331+332 .. py:data:: JSONIFY_MIMETYPE333 334 The mimetype of ``jsonify`` responses.335 336 Default: ``'application/json'``337 338+ .. deprecated:: 2.2339+ Will be removed in Flask 2.3. Set ``app.json.mimetype`` instead.340+341 .. py:data:: TEMPLATES_AUTO_RELOAD342 343 Reload templates when they are changed. If not set, it will be enabled in344 debug mode.56 unmodified lines401 402 .. versionchanged:: 2.2403 Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.404 405+.. versionchanged:: 2.2406+ ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``,407+ ``JSONIFY_MIMETYPE``, and ``JSONIFY_PRETTYPRINT_REGULAR`` will be408+ removed in Flask 2.3. The default ``app.json`` provider has409+ equivalent attributes instead.410 411+412 Configuring from Python Files413 -----------------------------414 415 Configuration becomes more useful if you can store it in a separate file,387 unmodified linesmodified:src/flask/json/__init__.py+200 added-162 removed
1-import dataclasses2-import decimal1+from __future__ import annotations2+3 import json as _json4 import typing as t5-import uuid6-from datetime import date5 6 from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9-from werkzeug.http import http_date7 8 from ..globals import current_app12-from ..globals import request9+from .provider import _default10 11 if t.TYPE_CHECKING: # pragma: no cover12 from ..app import Flask13 from ..wrappers import Response13 unmodified lines27 method) will call the ``__html__`` method to get a string.28 29 Assign a subclass of this to :attr:`flask.Flask.json_encoder` or30 :attr:`flask.Blueprint.json_encoder` to override the default.31+32+ .. deprecated:: 2.233+ Will be removed in Flask 2.3. Use ``app.json`` instead.34 """35 36+ def __init__(self, **kwargs) -> None:37+ import warnings38+39+ warnings.warn(40+ "'JSONEncoder' is deprecated and will be removed in"41+ " Flask 2.3. Use 'Flask.json' to provide an alternate"42+ " JSON implementation instead.",43+ DeprecationWarning,44+ stacklevel=3,45+ )46+ super().__init__(**kwargs)47+48 def default(self, o: t.Any) -> t.Any:49 """Convert ``o`` to a JSON serializable type. See50 :meth:`json.JSONEncoder.default`. Python does not support51 overriding how basic types like ``str`` or ``list`` are52 serialized, they are handled before this method.53 """42- if isinstance(o, date):43- return http_date(o)44- if isinstance(o, (decimal.Decimal, uuid.UUID)):45- return str(o)46- if dataclasses and dataclasses.is_dataclass(o):47- return dataclasses.asdict(o)48- if hasattr(o, "__html__"):49- return str(o.__html__())50- return super().default(o)54+ return _default(o)55 56 57 class JSONDecoder(_json.JSONDecoder):58 """The default JSON decoder.2 unmodified lines61 :class:`json.JSONDecoder`.62 63 Assign a subclass of this to :attr:`flask.Flask.json_decoder` or64 :attr:`flask.Blueprint.json_decoder` to override the default.65+66+ .. deprecated:: 2.267+ Will be removed in Flask 2.3. Use ``app.json`` instead.68 """69 70+ def __init__(self, **kwargs) -> None:71+ import warnings72 64-def _dump_arg_defaults(65- kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None66-) -> None:67- """Inject default arguments for dump functions."""68- if app is None:69- app = current_app73+ warnings.warn(74+ "'JSONDecoder' is deprecated and will be removed in"75+ " Flask 2.3. Use 'Flask.json' to provide an alternate"76+ " JSON implementation instead.",77+ DeprecationWarning,78+ stacklevel=3,79+ )80+ super().__init__(**kwargs)81 71- if app:72- cls = app.json_encoder73- bp = app.blueprints.get(request.blueprint) if request else None # type: ignore74- if bp is not None and bp.json_encoder is not None:75- cls = bp.json_encoder82 77- # Only set a custom encoder if it has custom behavior. This is78- # faster on PyPy.79- if cls is not _json.JSONEncoder:80- kwargs.setdefault("cls", cls)83+def dumps(obj: t.Any, *, app: Flask | None = None, **kwargs: t.Any) -> str:84+ """Serialize data as JSON.85 82- kwargs.setdefault("cls", cls)83- kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])84- kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])85- else:86- kwargs.setdefault("sort_keys", True)87- kwargs.setdefault("cls", JSONEncoder)86+ If :data:`~flask.current_app` is available, it will use its87+ :meth:`app.json.dumps() <flask.json.provider.JSONProvider.dumps>`88+ method, otherwise it will use :func:`json.dumps`.89 90+ :param obj: The data to serialize.91+ :param kwargs: Arguments passed to the ``dumps`` implementation.92 90-def _load_arg_defaults(91- kwargs: t.Dict[str, t.Any], app: t.Optional["Flask"] = None92-) -> None:93- """Inject default arguments for load functions."""94- if app is None:95- app = current_app93+ .. versionchanged:: 2.294+ Calls ``current_app.json.dumps``, allowing an app to override95+ the behavior.96 97- if app:98- cls = app.json_decoder99- bp = app.blueprints.get(request.blueprint) if request else None # type: ignore100- if bp is not None and bp.json_decoder is not None:101- cls = bp.json_decoder97+ .. versionchanged:: 2.298+ The ``app`` parameter will be removed in Flask 2.3.99 103- # Only set a custom decoder if it has custom behavior. This is104- # faster on PyPy.105- if cls not in {JSONDecoder, _json.JSONDecoder}:106- kwargs.setdefault("cls", cls)107-108-109-def dumps(obj: t.Any, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> str:110- """Serialize an object to a string of JSON.111-112- Takes the same arguments as the built-in :func:`json.dumps`, with113- some defaults from application configuration.114-115- :param obj: Object to serialize to JSON.116- :param app: Use this app's config instead of the active app context117- or defaults.118- :param kwargs: Extra arguments passed to :func:`json.dumps`.119-100 .. versionchanged:: 2.0.2101 :class:`decimal.Decimal` is supported by converting to a string.102 103 .. versionchanged:: 2.0124- ``encoding`` is deprecated and will be removed in Flask 2.1.104+ ``encoding`` will be removed in Flask 2.1.105 106 .. versionchanged:: 1.0.3107 ``app`` can be passed directly, rather than requiring an app108 context for configuration.109 """130- _dump_arg_defaults(kwargs, app=app)110+ if app is not None:111+ import warnings112+113+ warnings.warn(114+ "The 'app' parameter is deprecated and will be removed in"115+ " Flask 2.3. Call 'app.json.dumps' directly instead.",116+ DeprecationWarning,117+ stacklevel=2,118+ )119+ else:120+ app = current_app121+122+ if app:123+ return app.json.dumps(obj, **kwargs)124+125+ kwargs.setdefault("default", _default)126 return _json.dumps(obj, **kwargs)127 128 129 def dump(135- obj: t.Any, fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any130+ obj: t.Any, fp: t.IO[str], *, app: Flask | None = None, **kwargs: t.Any131 ) -> None:137- """Serialize an object to JSON written to a file object.132+ """Serialize data as JSON and write to a file.133 139- Takes the same arguments as the built-in :func:`json.dump`, with140- some defaults from application configuration.134+ If :data:`~flask.current_app` is available, it will use its135+ :meth:`app.json.dump() <flask.json.provider.JSONProvider.dump>`136+ method, otherwise it will use :func:`json.dump`.137 142- :param obj: Object to serialize to JSON.143- :param fp: File object to write JSON to.144- :param app: Use this app's config instead of the active app context145- or defaults.146- :param kwargs: Extra arguments passed to :func:`json.dump`.138+ :param obj: The data to serialize.139+ :param fp: A file opened for writing text. Should use the UTF-8140+ encoding to be valid JSON.141+ :param kwargs: Arguments passed to the ``dump`` implementation.142 143+ .. versionchanged:: 2.2144+ Calls ``current_app.json.dump``, allowing an app to override145+ the behavior.146+147+ .. versionchanged:: 2.2148+ The ``app`` parameter will be removed in Flask 2.3.149+150 .. versionchanged:: 2.0149- Writing to a binary file, and the ``encoding`` argument, is150- deprecated and will be removed in Flask 2.1.151+ Writing to a binary file, and the ``encoding`` argument, will be152+ removed in Flask 2.1.153 """152- _dump_arg_defaults(kwargs, app=app)153- _json.dump(obj, fp, **kwargs)154+ if app is not None:155+ import warnings156 157+ warnings.warn(158+ "The 'app' parameter is deprecated and will be removed in"159+ " Flask 2.3. Call 'app.json.dump' directly instead.",160+ DeprecationWarning,161+ stacklevel=2,162+ )163+ else:164+ app = current_app165 156-def loads(157- s: t.Union[str, bytes],158- app: t.Optional["Flask"] = None,159- **kwargs: t.Any,160-) -> t.Any:161- """Deserialize an object from a string of JSON.166+ if app:167+ app.json.dump(obj, fp, **kwargs)168+ else:169+ kwargs.setdefault("default", _default)170+ _json.dump(obj, fp, **kwargs)171 163- Takes the same arguments as the built-in :func:`json.loads`, with164- some defaults from application configuration.172 166- :param s: JSON string to deserialize.167- :param app: Use this app's config instead of the active app context168- or defaults.169- :param kwargs: Extra arguments passed to :func:`json.loads`.173+def loads(s: str | bytes, *, app: Flask | None = None, **kwargs: t.Any) -> t.Any:174+ """Deserialize data as JSON.175 176+ If :data:`~flask.current_app` is available, it will use its177+ :meth:`app.json.loads() <flask.json.provider.JSONProvider.loads>`178+ method, otherwise it will use :func:`json.loads`.179+180+ :param s: Text or UTF-8 bytes.181+ :param kwargs: Arguments passed to the ``loads`` implementation.182+183+ .. versionchanged:: 2.2184+ Calls ``current_app.json.loads``, allowing an app to override185+ the behavior.186+187+ .. versionchanged:: 2.2188+ The ``app`` parameter will be removed in Flask 2.3.189+190 .. versionchanged:: 2.0172- ``encoding`` is deprecated and will be removed in Flask 2.1. The173- data must be a string or UTF-8 bytes.191+ ``encoding`` will be removed in Flask 2.1. The data must be a192+ string or UTF-8 bytes.193 194 .. versionchanged:: 1.0.3195 ``app`` can be passed directly, rather than requiring an app196 context for configuration.197 """179- _load_arg_defaults(kwargs, app=app)198+ if app is not None:199+ import warnings200+201+ warnings.warn(202+ "The 'app' parameter is deprecated and will be removed in"203+ " Flask 2.3. Call 'app.json.loads' directly instead.",204+ DeprecationWarning,205+ stacklevel=2,206+ )207+ else:208+ app = current_app209+210+ if app:211+ return app.json.loads(s, **kwargs)212+213 return _json.loads(s, **kwargs)214 215 183-def load(fp: t.IO[str], app: t.Optional["Flask"] = None, **kwargs: t.Any) -> t.Any:184- """Deserialize an object from JSON read from a file object.216+def load(fp: t.IO[t.AnyStr], *, app: Flask | None = None, **kwargs: t.Any) -> t.Any:217+ """Deserialize data as JSON read from a file.218 186- Takes the same arguments as the built-in :func:`json.load`, with187- some defaults from application configuration.219+ If :data:`~flask.current_app` is available, it will use its220+ :meth:`app.json.load() <flask.json.provider.JSONProvider.load>`221+ method, otherwise it will use :func:`json.load`.222 189- :param fp: File object to read JSON from.190- :param app: Use this app's config instead of the active app context191- or defaults.192- :param kwargs: Extra arguments passed to :func:`json.load`.223+ :param fp: A file opened for reading text or UTF-8 bytes.224+ :param kwargs: Arguments passed to the ``load`` implementation.225 226+ .. versionchanged:: 2.2227+ Calls ``current_app.json.load``, allowing an app to override228+ the behavior.229+230+ .. versionchanged:: 2.2231+ The ``app`` parameter will be removed in Flask 2.3.232+233 .. versionchanged:: 2.0195- ``encoding`` is deprecated and will be removed in Flask 2.1. The196- file must be text mode, or binary mode with UTF-8 bytes.234+ ``encoding`` will be removed in Flask 2.1. The file must be text235+ mode, or binary mode with UTF-8 bytes.236 """198- _load_arg_defaults(kwargs, app=app)237+ if app is not None:238+ import warnings239+240+ warnings.warn(241+ "The 'app' parameter is deprecated and will be removed in"242+ " Flask 2.3. Call 'app.json.load' directly instead.",243+ DeprecationWarning,244+ stacklevel=2,245+ )246+ else:247+ app = current_app248+249+ if app:250+ return app.json.load(fp, **kwargs)251+252 return _json.load(fp, **kwargs)253 254 255 def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:7 unmodified lines263 ``<script>`` tags. The exception is in HTML attributes that are264 double quoted; either use single quotes or the ``|forceescape``265 filter.266 267+ .. deprecated:: 2.2268+ Will be removed in Flask 2.3. This is built-in to Jinja now.269+270 .. versionchanged:: 2.0271 Uses :func:`jinja2.utils.htmlsafe_json_dumps`. The returned272 value is marked safe by wrapping in :class:`~markupsafe.Markup`.273 1 unmodified line275 Single quotes are escaped, making this safe to use in HTML,276 ``<script>`` tags, and single-quoted attributes without further277 escaping.278 """279+ import warnings280+281+ warnings.warn(282+ "'htmlsafe_dumps' is deprecated and will be removed in Flask"283+ " 2.3. Use 'jinja2.utils.htmlsafe_json_dumps' instead.",284+ DeprecationWarning,285+ stacklevel=2,286+ )287 return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)288 289 290 def htmlsafe_dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:291 """Serialize an object to JSON written to a file object, replacing292 HTML-unsafe characters with Unicode escapes. See293 :func:`htmlsafe_dumps` and :func:`dumps`.294+295+ .. deprecated:: 2.2296+ Will be removed in Flask 2.3.297 """298+ import warnings299+300+ warnings.warn(301+ "'htmlsafe_dump' is deprecated and will be removed in Flask"302+ " 2.3. Use 'jinja2.utils.htmlsafe_json_dumps' instead.",303+ DeprecationWarning,304+ stacklevel=2,305+ )306 fp.write(htmlsafe_dumps(obj, **kwargs))307 308 234-def jsonify(*args: t.Any, **kwargs: t.Any) -> "Response":235- """Serialize data to JSON and wrap it in a :class:`~flask.Response`236- with the :mimetype:`application/json` mimetype.309+def jsonify(*args: t.Any, **kwargs: t.Any) -> Response:310+ """Serialize the given arguments as JSON, and return a311+ :class:`~flask.Response` object with the ``application/json``312+ mimetype. A dict or list returned from a view will be converted to a313+ JSON response automatically without needing to call this.314 238- Uses :func:`dumps` to serialize the data, but ``args`` and239- ``kwargs`` are treated as data rather than arguments to240- :func:`json.dumps`.315+ This requires an active request or application context, and calls316+ :meth:`app.json.response() <flask.json.provider.JSONProvider.response>`.317 242- 1. Single argument: Treated as a single value.243- 2. Multiple arguments: Treated as a list of values.244- ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.245- 3. Keyword arguments: Treated as a dict of values.246- ``jsonify(data=data, errors=errors)`` is the same as247- ``jsonify({"data": data, "errors": errors})``.248- 4. Passing both arguments and keyword arguments is not allowed as249- it's not clear what should happen.318+ In debug mode, the output is formatted with indentation to make it319+ easier to read. This may also be controlled by the provider.320 251- .. code-block:: python321+ Either positional or keyword arguments can be given, not both.322+ If no arguments are given, ``None`` is serialized.323 253- from flask import jsonify324+ :param args: A single value to serialize, or multiple values to325+ treat as a list to serialize.326+ :param kwargs: Treat as a dict to serialize.327 255- @app.route("/users/me")256- def get_current_user():257- return jsonify(258- username=g.user.username,259- email=g.user.email,260- id=g.user.id,261- )328+ .. versionchanged:: 2.2329+ Calls ``current_app.json.response``, allowing an app to override330+ the behavior.331 263- Will return a JSON response like this:264-265- .. code-block:: javascript266-267- {268- "username": "admin",269- "email": "admin@localhost",270- "id": 42271- }272-273- The default output omits indents and spaces after separators. In274- debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,275- the output will be formatted to be easier to read.276-332 .. versionchanged:: 2.0.2333 :class:`decimal.Decimal` is supported by converting to a string.334 335 .. versionchanged:: 0.11281- Added support for serializing top-level arrays. This introduces282- a security risk in ancient browsers. See :ref:`security-json`.336+ Added support for serializing top-level arrays. This was a337+ security risk in ancient browsers. See :ref:`security-json`.338 339 .. versionadded:: 0.2340 """286- indent = None287- separators = (",", ":")288-289- if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:290- indent = 2291- separators = (", ", ": ")292-293- if args and kwargs:294- raise TypeError("jsonify() behavior undefined when passed both args and kwargs")295- elif len(args) == 1: # single args are passed directly to dumps()296- data = args[0]297- else:298- data = args or kwargs299-300- return current_app.response_class(301- f"{dumps(data, indent=indent, separators=separators)}\n",302- mimetype=current_app.config["JSONIFY_MIMETYPE"],303- )341+ return current_app.json.response(*args, **kwargs)added:src/flask/json/provider.py+310 added
1+from __future__ import annotations2+3+import dataclasses4+import decimal5+import json6+import typing as t7+import uuid8+import weakref9+from datetime import date10+11+from werkzeug.http import http_date12+13+from ..globals import request14+15+if t.TYPE_CHECKING: # pragma: no cover16+ from ..app import Flask17+ from ..wrappers import Response18+19+20+class JSONProvider:21+ """A standard set of JSON operations for an application. Subclasses22+ of this can be used to customize JSON behavior or use different23+ JSON libraries.24+25+ To implement a provider for a specific library, subclass this base26+ class and implement at least :meth:`dumps` and :meth:`loads`. All27+ other methods have default implementations.28+29+ To use a different provider, either subclass ``Flask`` and set30+ :attr:`~flask.Flask.json_provider_class` to a provider class, or set31+ :attr:`app.json <flask.Flask.json>` to an instance of the class.32+33+ :param app: An application instance. This will be stored as a34+ :class:`weakref.proxy` on the :attr:`_app` attribute.35+36+ .. versionadded:: 2.237+ """38+39+ def __init__(self, app: Flask) -> None:40+ self._app = weakref.proxy(app)41+42+ def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:43+ """Serialize data as JSON.44+45+ :param obj: The data to serialize.46+ :param kwargs: May be passed to the underlying JSON library.47+ """48+ raise NotImplementedError49+50+ def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:51+ """Serialize data as JSON and write to a file.52+53+ :param obj: The data to serialize.54+ :param fp: A file opened for writing text. Should use the UTF-855+ encoding to be valid JSON.56+ :param kwargs: May be passed to the underlying JSON library.57+ """58+ fp.write(self.dumps(obj, **kwargs))59+60+ def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:61+ """Deserialize data as JSON.62+63+ :param s: Text or UTF-8 bytes.64+ :param kwargs: May be passed to the underlying JSON library.65+ """66+ raise NotImplementedError67+68+ def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:69+ """Deserialize data as JSON read from a file.70+71+ :param fp: A file opened for reading text or UTF-8 bytes.72+ :param kwargs: May be passed to the underlying JSON library.73+ """74+ return self.loads(fp.read(), **kwargs)75+76+ def _prepare_response_obj(77+ self, args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]78+ ) -> t.Any:79+ if args and kwargs:80+ raise TypeError("app.json.response() takes either args or kwargs, not both")81+82+ if not args and not kwargs:83+ return None84+85+ if len(args) == 1:86+ return args[0]87+88+ return args or kwargs89+90+ def response(self, *args: t.Any, **kwargs: t.Any) -> Response:91+ """Serialize the given arguments as JSON, and return a92+ :class:`~flask.Response` object with the ``application/json``93+ mimetype.94+95+ The :func:`~flask.json.jsonify` function calls this method for96+ the current application.97+98+ Either positional or keyword arguments can be given, not both.99+ If no arguments are given, ``None`` is serialized.100+101+ :param args: A single value to serialize, or multiple values to102+ treat as a list to serialize.103+ :param kwargs: Treat as a dict to serialize.104+ """105+ obj = self._prepare_response_obj(args, kwargs)106+ return self._app.response_class(self.dumps(obj), mimetype="application/json")107+108+109+def _default(o: t.Any) -> t.Any:110+ if isinstance(o, date):111+ return http_date(o)112+113+ if isinstance(o, (decimal.Decimal, uuid.UUID)):114+ return str(o)115+116+ if dataclasses and dataclasses.is_dataclass(o):117+ return dataclasses.asdict(o)118+119+ if hasattr(o, "__html__"):120+ return str(o.__html__())121+122+ raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")123+124+125+class DefaultJSONProvider(JSONProvider):126+ """Provide JSON operations using Python's built-in :mod:`json`127+ library. Serializes the following additional data types:128+129+ - :class:`datetime.datetime` and :class:`datetime.date` are130+ serialized to :rfc:`822` strings. This is the same as the HTTP131+ date format.132+ - :class:`uuid.UUID` is serialized to a string.133+ - :class:`dataclasses.dataclass` is passed to134+ :func:`dataclasses.asdict`.135+ - :class:`~markupsafe.Markup` (or any object with a ``__html__``136+ method) will call the ``__html__`` method to get a string.137+ """138+139+ default: t.Callable[[t.Any], t.Any] = staticmethod(140+ _default141+ ) # type: ignore[assignment]142+ """Apply this function to any object that :meth:`json.dumps` does143+ not know how to serialize. It should return a valid JSON type or144+ raise a ``TypeError``.145+ """146+147+ ensure_ascii = True148+ """Replace non-ASCII characters with escape sequences. This may be149+ more compatible with some clients, but can be disabled for better150+ performance and size.151+ """152+153+ sort_keys = True154+ """Sort the keys in any serialized dicts. This may be useful for155+ some caching situations, but can be disabled for better performance.156+ When enabled, keys must all be strings, they are not converted157+ before sorting.158+ """159+160+ compact: bool | None = None161+ """If ``True``, or ``None`` out of debug mode, the :meth:`response`162+ output will not add indentation, newlines, or spaces. If ``False``,163+ or ``None`` in debug mode, it will use a non-compact representation.164+ """165+166+ mimetype = "application/json"167+ """The mimetype set in :meth:`response`."""168+169+ def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:170+ """Serialize data as JSON to a string.171+172+ Keyword arguments are passed to :func:`json.dumps`. Sets some173+ parameter defaults from the :attr:`default`,174+ :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.175+176+ :param obj: The data to serialize.177+ :param kwargs: Passed to :func:`json.dumps`.178+ """179+ cls = self._app.json_encoder180+ bp = self._app.blueprints.get(request.blueprint) if request else None181+182+ if bp is not None and bp.json_encoder is not None:183+ cls = bp.json_encoder184+185+ if cls is not None:186+ import warnings187+188+ warnings.warn(189+ "Setting 'json_encoder' on the app or a blueprint is"190+ " deprecated and will be removed in Flask 2.3."191+ " Customize 'app.json' instead.",192+ DeprecationWarning,193+ )194+ kwargs.setdefault("cls", cls)195+196+ if "default" not in cls.__dict__:197+ kwargs.setdefault("default", self.default)198+ else:199+ kwargs.setdefault("default", self.default)200+201+ ensure_ascii = self._app.config["JSON_AS_ASCII"]202+ sort_keys = self._app.config["JSON_SORT_KEYS"]203+204+ if ensure_ascii is not None:205+ import warnings206+207+ warnings.warn(208+ "The 'JSON_AS_ASCII' config key is deprecated and will"209+ " be removed in Flask 2.3. Set 'app.json.ensure_ascii'"210+ " instead.",211+ DeprecationWarning,212+ )213+ else:214+ ensure_ascii = self.ensure_ascii215+216+ if sort_keys is not None:217+ import warnings218+219+ warnings.warn(220+ "The 'JSON_SORT_KEYS' config key is deprecated and will"221+ " be removed in Flask 2.3. Set 'app.json.sort_keys'"222+ " instead.",223+ DeprecationWarning,224+ )225+ else:226+ sort_keys = self.sort_keys227+228+ kwargs.setdefault("ensure_ascii", ensure_ascii)229+ kwargs.setdefault("sort_keys", sort_keys)230+ return json.dumps(obj, **kwargs)231+232+ def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:233+ """Deserialize data as JSON from a string or bytes.234+235+ :param s: Text or UTF-8 bytes.236+ :param kwargs: Passed to :func:`json.loads`.237+ """238+ cls = self._app.json_decoder239+ bp = self._app.blueprints.get(request.blueprint) if request else None240+241+ if bp is not None and bp.json_decoder is not None:242+ cls = bp.json_decoder243+244+ if cls is not None:245+ import warnings246+247+ warnings.warn(248+ "Setting 'json_decoder' on the app or a blueprint is"249+ " deprecated and will be removed in Flask 2.3."250+ " Customize 'app.json' instead.",251+ DeprecationWarning,252+ )253+ kwargs.setdefault("cls", cls)254+255+ return json.loads(s, **kwargs)256+257+ def response(self, *args: t.Any, **kwargs: t.Any) -> Response:258+ """Serialize the given arguments as JSON, and return a259+ :class:`~flask.Response` object with it. The response mimetype260+ will be "application/json" and can be changed with261+ :attr:`mimetype`.262+263+ If :attr:`compact` is ``False`` or debug mode is enabled, the264+ output will be formatted to be easier to read.265+266+ Either positional or keyword arguments can be given, not both.267+ If no arguments are given, ``None`` is serialized.268+269+ :param args: A single value to serialize, or multiple values to270+ treat as a list to serialize.271+ :param kwargs: Treat as a dict to serialize.272+ """273+ obj = self._prepare_response_obj(args, kwargs)274+ dump_args: t.Dict[str, t.Any] = {}275+ pretty = self._app.config["JSONIFY_PRETTYPRINT_REGULAR"]276+ mimetype = self._app.config["JSONIFY_MIMETYPE"]277+278+ if pretty is not None:279+ import warnings280+281+ warnings.warn(282+ "The 'JSONIFY_PRETTYPRINT_REGULAR' config key is"283+ " deprecated and will be removed in Flask 2.3. Set"284+ " 'app.json.compact' instead.",285+ DeprecationWarning,286+ )287+ compact: bool | None = not pretty288+ else:289+ compact = self.compact290+291+ if (compact is None and self._app.debug) or compact is False:292+ dump_args.setdefault("indent", 2)293+ else:294+ dump_args.setdefault("separators", (",", ":"))295+296+ if mimetype is not None:297+ import warnings298+299+ warnings.warn(300+ "The 'JSONIFY_MIMETYPE' config key is deprecated and"301+ " will be removed in Flask 2.3. Set 'app.json.mimetype'"302+ " instead.",303+ DeprecationWarning,304+ )305+ else:306+ mimetype = self.mimetype307+308+ return self._app.response_class(309+ f"{self.dumps(obj, **dump_args)}\n", mimetype=mimetype310+ )modified:src/flask/app.py+50 added-12 removed
29 unmodified lines30 from werkzeug.utils import redirect as _wz_redirect31 from werkzeug.wrappers import Response as BaseResponse32 33 from . import cli34-from . import json34 from . import typing as ft35 from .config import Config36 from .config import ConfigAttribute37 from .ctx import _AppCtxGlobals10 unmodified lines48 from .helpers import get_env49 from .helpers import get_flashed_messages50 from .helpers import get_load_dotenv51 from .helpers import locked_cached_property53-from .json import jsonify52+from .json.provider import DefaultJSONProvider53+from .json.provider import JSONProvider54 from .logging import create_logger55 from .scaffold import _endpoint_from_view_func56 from .scaffold import _sentinel57 from .scaffold import find_package256 unmodified lines314 #: This attribute can also be configured from the config with the315 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.316 use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")317 318- #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.318+ #: The JSON encoder class to use. Defaults to319+ #: :class:`~flask.json.JSONEncoder`.320 #:321+ #: .. deprecated:: 2.2322+ #: Will be removed in Flask 2.3. Customize323+ #: :attr:`json_provider_class` instead.324+ #:325 #: .. versionadded:: 0.10321- json_encoder = json.JSONEncoder326+ json_encoder: None = None327 323- #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.328+ #: The JSON decoder class to use. Defaults to329+ #: :class:`~flask.json.JSONDecoder`.330 #:331+ #: .. deprecated:: 2.2332+ #: Will be removed in Flask 2.3. Customize333+ #: :attr:`json_provider_class` instead.334+ #:335 #: .. versionadded:: 0.10326- json_decoder = json.JSONDecoder336+ json_decoder: None = None337 338+ json_provider_class: t.Type[JSONProvider] = DefaultJSONProvider339+ """A subclass of :class:`~flask.json.provider.JSONProvider`. An340+ instance is created and assigned to :attr:`app.json` when creating341+ the app.342+343+ The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses344+ Python's built-in :mod:`json` library. A different provider can use345+ a different JSON library.346+347+ .. versionadded:: 2.2348+ """349+350 #: Options that are passed to the Jinja environment in351 #: :meth:`create_jinja_environment`. Changing these options after352 #: the environment is created (accessing :attr:`jinja_env`) will353 #: have no effect.28 unmodified lines382 "TRAP_BAD_REQUEST_ERRORS": None,383 "TRAP_HTTP_EXCEPTIONS": False,384 "EXPLAIN_TEMPLATE_LOADING": False,385 "PREFERRED_URL_SCHEME": "http",364- "JSON_AS_ASCII": True,365- "JSON_SORT_KEYS": True,366- "JSONIFY_PRETTYPRINT_REGULAR": False,367- "JSONIFY_MIMETYPE": "application/json",386+ "JSON_AS_ASCII": None,387+ "JSON_SORT_KEYS": None,388+ "JSONIFY_PRETTYPRINT_REGULAR": None,389+ "JSONIFY_MIMETYPE": None,390 "TEMPLATES_AUTO_RELOAD": None,391 "MAX_COOKIE_SIZE": 4093,392 }393 )76 unmodified lines470 #: .. versionadded:: 2.2471 #: Moved from ``flask.abort``, which calls this object.472 self.aborter = self.make_aborter()473 474+ self.json: JSONProvider = self.json_provider_class(self)475+ """Provides access to JSON methods. Functions in ``flask.json``476+ will call methods on this provider when the application context477+ is active. Used for handling JSON requests and responses.478+479+ An instance of :attr:`json_provider_class`. Can be customized by480+ changing that attribute on a subclass, or by assigning to this481+ attribute afterwards.482+483+ The default, :class:`~flask.json.provider.DefaultJSONProvider`,484+ uses Python's built-in :mod:`json` library. A different provider485+ can use a different JSON library.486+487+ .. versionadded:: 2.2488+ """489+490 #: A list of functions that are called by491 #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a492 #: :exc:`~werkzeug.routing.BuildError`. Each function is called493 #: with ``error``, ``endpoint`` and ``values``. If a function288 unmodified lines782 request=request,783 session=session,784 g=g,785 )748- rv.policies["json.dumps_function"] = json.dumps786+ rv.policies["json.dumps_function"] = self.json.dumps787 return rv788 789 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:790 """Creates the loader for the Jinja2 environment. Can be used to1172 unmodified lines1963 headers=headers, # type: ignore[arg-type]1964 )1965 status = headers = None1966 elif isinstance(rv, (dict, list)):1929- rv = jsonify(rv)1967+ rv = self.json.response(rv)1968 elif isinstance(rv, BaseResponse) or callable(rv):1969 # evaluate a WSGI callable, or coerce a different response1970 # class to the correct type1971 try:391 unmodified linesmodified:src/flask/blueprints.py+8 added-2 removed
172 unmodified lines173 _got_registered_once = False174 175 #: Blueprint local JSON encoder class to use. Set to ``None`` to use176 #: the app's :class:`~flask.Flask.json_encoder`.177+ #:178+ #: .. deprecated:: 2.2179+ #: Will be removed in Flask 2.3.177- json_encoder = None180+ json_encoder: None = None181 #: Blueprint local JSON decoder class to use. Set to ``None`` to use182 #: the app's :class:`~flask.Flask.json_decoder`.183+ #:184+ #: .. deprecated:: 2.2185+ #: Will be removed in Flask 2.3.180- json_decoder = None186+ json_decoder: None = None187 188 def __init__(189 self,190 name: str,457 unmodified linesmodified:src/flask/ctx.py+1 added
305 unmodified lines306 ) -> None:307 self.app = app308 if request is None:309 request = app.request_class(environ)310+ request.json_module = app.json # type: ignore[misc]311 self.request: Request = request312 self.url_adapter = None313 try:314 self.url_adapter = app.create_url_adapter(self.request)124 unmodified linesmodified:src/flask/scaffold.py+8 added-4 removed
4 unmodified lines5 import sys6 import typing as t7 from collections import defaultdict8 from functools import update_wrapper9-from json import JSONDecoder10-from json import JSONEncoder9 10 from jinja2 import FileSystemLoader11 from werkzeug.exceptions import default_exceptions12 from werkzeug.exceptions import HTTPException60 unmodified lines73 _static_url_path: t.Optional[str] = None74 75 #: JSON encoder class used by :func:`flask.json.dumps`. If a76 #: blueprint sets this, it will be used instead of the app's value.79- json_encoder: t.Optional[t.Type[JSONEncoder]] = None77+ #:78+ #: .. deprecated:: 2.279+ #: Will be removed in Flask 2.3.80+ json_encoder: None = None81 82 #: JSON decoder class used by :func:`flask.json.loads`. If a83 #: blueprint sets this, it will be used instead of the app's value.83- json_decoder: t.Optional[t.Type[JSONDecoder]] = None84+ #:85+ #: .. deprecated:: 2.286+ #: Will be removed in Flask 2.3.87+ json_decoder: None = None88 89 def __init__(90 self,91 import_name: str,802 unmodified linesmodified:src/flask/testing.py+2 added-3 removed
10 unmodified lines11 from werkzeug.wrappers import Request as BaseRequest12 13 from .cli import ScriptInfo14 from .globals import _cv_request15-from .json import dumps as json_dumps15 from .sessions import SessionMixin16 17 if t.TYPE_CHECKING: # pragma: no cover18 from werkzeug.test import TestResponse68 unmodified lines87 88 The serialization will be configured according to the config associated89 with this EnvironBuilder's ``app``.90 """92- kwargs.setdefault("app", self.app)93- return json_dumps(obj, **kwargs)91+ return self.app.json.dumps(obj, **kwargs)92 93 94 class FlaskClient(Client):95 """Works like a regular Werkzeug test client but has knowledge about128 unmodified lines224 request,225 buffered=buffered,226 follow_redirects=follow_redirects,227 )228+ response.json_module = self.application.json # type: ignore[misc]229 230 # Re-push contexts that were preserved during the request.231 while self._new_contexts:232 cm = self._new_contexts.pop()54 unmodified linesmodified:tests/test_basic.py+11 added-22 removed
1300 unmodified lines1301 assert rv.headers["Content-Type"] == "text/html"1302 assert rv.headers["X-Foo"] == "bar"1303 1304 1305-def test_jsonify_no_prettyprint(app, req_ctx):1306- app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1307- compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1308- uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1305+@pytest.mark.parametrize("compact", [True, False])1306+def test_jsonify_no_prettyprint(app, compact):1307+ app.json.compact = compact1308+ rv = app.json.response({"msg": {"submsg": "W00t"}, "msg2": "foobar"})1309+ data = rv.data.strip()1310+ assert (b" " not in data) is compact1311+ assert (b"\n" not in data) is compact1312 1310- rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1311- assert rv.data == compressed_msg1313 1313-1314-def test_jsonify_prettyprint(app, req_ctx):1315- app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1316- compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1317- pretty_response = (1318- b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1319- )1320-1321- rv = flask.make_response(flask.jsonify(compressed_msg), 200)1322- assert rv.data == pretty_response1323-1324-1314 def test_jsonify_mimetype(app, req_ctx):1326- app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1315+ app.json.mimetype = "application/vnd.api+json"1316 msg = {"msg": {"submsg": "W00t"}}1317 rv = flask.make_response(flask.jsonify(msg), 200)1318 assert rv.mimetype == "application/vnd.api+json"1319 1 unmodified line1321 def test_json_dump_dataclass(app, req_ctx):1322 from dataclasses import make_dataclass1323 1324 Data = make_dataclass("Data", [("name", str)])1336- value = flask.json.dumps(Data("Flask"), app=app)1337- value = flask.json.loads(value, app=app)1325+ value = app.json.dumps(Data("Flask"))1326+ value = app.json.loads(value)1327 assert value == {"name": "Flask"}1328 1329 1330 def test_jsonify_args_and_kwargs_check(app, req_ctx):1331 with pytest.raises(TypeError) as e:1332 flask.jsonify("fake args", kwargs="fake")1344- assert "behavior undefined" in str(e.value)1333+ assert "args or kwargs" in str(e.value)1334 1335 1336 def test_url_generation(app, req_ctx):1337 @app.route("/hello/<name>", methods=["POST"])621 unmodified linesmodified:tests/test_json.py+17 added-60 removed
6 unmodified lines7 from werkzeug.http import http_date8 9 import flask10 from flask import json11+from flask.json.provider import DefaultJSONProvider12 13 14 @pytest.mark.parametrize("debug", (True, False))15 def test_bad_request_debug_message(app, client, debug):32 unmodified lines48 @pytest.mark.parametrize(49 "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')]50 )51 def test_json_as_unicode(test_value, expected, app, app_ctx):51-52- app.config["JSON_AS_ASCII"] = test_value53- rv = flask.json.dumps("\N{SNOWMAN}")52+ app.json.ensure_ascii = test_value53+ rv = app.json.dumps("\N{SNOWMAN}")54 assert rv == expected55 56 57 def test_json_dump_to_file(app, app_ctx):111 unmodified lines169 tzinfo = FixedOffset(hours=tz[1], name=tz[0])170 dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)171 gmt = FixedOffset(hours=0, name="GMT")172 expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')173- assert flask.json.JSONEncoder().encode(dt) == expected173+ assert flask.json.dumps(dt) == expected174 175 176 def test_jsonify_uuid_types(app, client):177 """Test jsonify with uuid.UUID types"""46 unmodified lines224 class X: # noqa: B903, for Python2 compatibility225 def __init__(self, val):226 self.val = val227 228- class MyEncoder(flask.json.JSONEncoder):229- def default(self, o):230- if isinstance(o, X):231- return f"<{o.val}>"228+ def default(o):229+ if isinstance(o, X):230+ return f"<{o.val}>"232- return flask.json.JSONEncoder.default(self, o)231 234- class MyDecoder(flask.json.JSONDecoder):235- def __init__(self, *args, **kwargs):236- kwargs.setdefault("object_hook", self.object_hook)237- flask.json.JSONDecoder.__init__(self, *args, **kwargs)232+ return DefaultJSONProvider.default(o)233 234+ class CustomProvider(DefaultJSONProvider):235 def object_hook(self, obj):236 if len(obj) == 1 and "_foo" in obj:237 return X(obj["_foo"])238+239 return obj240 244- app.json_encoder = MyEncoder245- app.json_decoder = MyDecoder241+ def loads(self, s, **kwargs):242+ kwargs.setdefault("object_hook", self.object_hook)243+ return super().loads(s, **kwargs)244 245+ app.json = CustomProvider(app)246+ app.json.default = default247+248 @app.route("/", methods=["POST"])249 def index():250 return flask.json.dumps(flask.request.get_json()["x"])251 4 unmodified lines256 )257 assert rv.data == b'"<42>"'258 259 259-def test_blueprint_json_customization(app, client):260- class X:261- __slots__ = ("val",)262-263- def __init__(self, val):264- self.val = val265-266- class MyEncoder(flask.json.JSONEncoder):267- def default(self, o):268- if isinstance(o, X):269- return f"<{o.val}>"270-271- return flask.json.JSONEncoder.default(self, o)272-273- class MyDecoder(flask.json.JSONDecoder):274- def __init__(self, *args, **kwargs):275- kwargs.setdefault("object_hook", self.object_hook)276- flask.json.JSONDecoder.__init__(self, *args, **kwargs)277-278- def object_hook(self, obj):279- if len(obj) == 1 and "_foo" in obj:280- return X(obj["_foo"])281-282- return obj283-284- bp = flask.Blueprint("bp", __name__)285- bp.json_encoder = MyEncoder286- bp.json_decoder = MyDecoder287-288- @bp.route("/bp", methods=["POST"])289- def index():290- return flask.json.dumps(flask.request.get_json()["x"])291-292- app.register_blueprint(bp)293-294- rv = client.post(295- "/bp",296- data=flask.json.dumps({"x": {"_foo": 42}}),297- content_type="application/json",298- )299- assert rv.data == b'"<42>"'300-301-260 def _has_encoding(name):261 try:262 import codecs263 23 unmodified lines287 288 289 def test_json_key_sorting(app, client):290 app.debug = True333-334- assert app.config["JSON_SORT_KEYS"]291+ assert app.json.sort_keys292 d = dict.fromkeys(range(20), "foo")293 294 @app.route("/")295 def index():70 unmodified linesmodified:tests/test_testing.py+1 added-1 removed
110 unmodified lines111 112 113 def test_environbuilder_json_dumps(app):114 """EnvironBuilder.json_dumps() takes settings from the app."""115- app.config["JSON_AS_ASCII"] = False115+ app.json.ensure_ascii = False116 eb = EnvironBuilder(app, json="\u20ac")117 assert eb.input_stream.read().decode("utf8") == '"\u20ac"'118 119 284 unmodified linesmodified:CHANGES.rst+15 added
30 unmodified lines31 - ``flask.abort`` will call ``app.aborter``.32 ``Flask.aborter_class`` and ``Flask.make_aborter`` can be used33 to customize this aborter. :issue:`4567`34 - ``flask.redirect`` will call ``app.redirect``. :issue:`4569`35+ - ``flask.json`` is an instance of ``JSONProvider``. A different36+ provider can be set to use a different JSON library.37+ ``flask.jsonify`` will call ``app.json.response``, other38+ functions in ``flask.json`` will call corresponding functions in39+ ``app.json``. :pr:`4688`40 41+- JSON configuration is moved to attributes on the default42+ ``app.json`` provider. ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``,43+ ``JSONIFY_MIMETYPE``, and ``JSONIFY_PRETTYPRINT_REGULAR`` are44+ deprecated. :pr:`4688`45+- Setting custom ``json_encoder`` and ``json_decoder`` classes on the46+ app or a blueprint, and the corresponding ``json.JSONEncoder`` and47+ ``JSONDecoder`` classes, are deprecated. JSON behavior can now be48+ overridden using the ``app.json`` provider interface. :pr:`4688`49+- ``json.htmlsafe_dumps`` and ``json.htmlsafe_dump`` are deprecated,50+ the function is built-in to Jinja now. :pr:`4688`51 - Refactor ``register_error_handler`` to consolidate error checking.52 Rewrite some error messages to be more consistent. :issue:`4559`53 - Use Blueprint decorators and functions intended for setup after54 registering the blueprint will show a warning. In the next version,1334 unmodified lines