Skip to content
Myr

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

13 files+662 added−282 removed

modified:docs/api.rst+16 added-14 removed
234 unmodified lines
235------------236237.. module:: flask.json238239Flask uses the built-in :mod:`json` module for handling JSON. It will240use the current blueprint's or application's JSON encoder and decoder241for easier customization. By default it handles some extra data types:239Flask uses Python's built-in :mod:`json` module for handling JSON by240default. The JSON implementation can be changed by assigning a different241provider to :attr:`flask.Flask.json_provider_class` or242:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will243use methods on ``app.json`` if an app context is active.244243- :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.245Jinja's ``|tojson`` filter is configured to use the app's JSON provider.246The filter marks the output with ``|safe``. Use it to render data inside247HTML ``<script>`` tags.248251Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`252function. The filter marks the output with ``|safe`` automatically. Use253the filter to render data inside ``<script>`` tags.254249.. sourcecode:: html+jinja250251 <script>252 const names = {{ names|tosjon }};
9 unmodified lines
262.. autofunction:: loads263264.. autofunction:: load265266.. autoclass:: flask.json.provider.JSONProvider267 :members:268 :member-order: bysource269270.. autoclass:: flask.json.provider.DefaultJSONProvider271 :members:272 :member-order: bysource273274.. autoclass:: JSONEncoder275 :members:276277.. autoclass:: JSONDecoder
474 unmodified lines
modified:docs/config.rst+23 added-2 removed
299 unmodified lines
300 templates, and should typically remain enabled.301302 Default: ``True``303304 .. deprecated:: 2.2305 Will be removed in Flask 2.3. Set ``app.json.ensure_ascii``306 instead.307308.. py:data:: JSON_SORT_KEYS309310 Sort the keys of JSON objects alphabetically. This is useful for caching311 because it ensures the data is serialized the same way no matter what
1 unmodified line
313 possible performance improvement at the cost of caching.314315 Default: ``True``316317 .. deprecated:: 2.2318 Will be removed in Flask 2.3. Set ``app.json.sort_keys``319 instead.320321.. py:data:: JSONIFY_PRETTYPRINT_REGULAR322315 ``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.326327 Default: ``False``328329 .. deprecated:: 2.2330 Will be removed in Flask 2.3. Set ``app.json.compact`` instead.331332.. py:data:: JSONIFY_MIMETYPE333334 The mimetype of ``jsonify`` responses.335336 Default: ``'application/json'``337338 .. deprecated:: 2.2339 Will be removed in Flask 2.3. Set ``app.json.mimetype`` instead.340341.. py:data:: TEMPLATES_AUTO_RELOAD342343 Reload templates when they are changed. If not set, it will be enabled in344 debug mode.
56 unmodified lines
401402.. versionchanged:: 2.2403 Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.404405.. 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.410411412Configuring from Python Files413-----------------------------414415Configuration becomes more useful if you can store it in a separate file,
387 unmodified lines
modified:src/flask/json/__init__.py+200 added-162 removed
1import dataclasses2import decimal1from __future__ import annotations23import json as _json4import typing as t5import uuid6from datetime import date56from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9from werkzeug.http import http_date78from ..globals import current_app12from ..globals import request9from .provider import _default1011if t.TYPE_CHECKING: # pragma: no cover12 from ..app import Flask13 from ..wrappers import Response
13 unmodified lines
27 method) will call the ``__html__`` method to get a string.2829 Assign a subclass of this to :attr:`flask.Flask.json_encoder` or30 :attr:`flask.Blueprint.json_encoder` to override the default.3132 .. deprecated:: 2.233 Will be removed in Flask 2.3. Use ``app.json`` instead.34 """3536 def __init__(self, **kwargs) -> None:37 import warnings3839 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)4748 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)555657class JSONDecoder(_json.JSONDecoder):58 """The default JSON decoder.
2 unmodified lines
61 :class:`json.JSONDecoder`.6263 Assign a subclass of this to :attr:`flask.Flask.json_decoder` or64 :attr:`flask.Blueprint.json_decoder` to override the default.6566 .. deprecated:: 2.267 Will be removed in Flask 2.3. Use ``app.json`` instead.68 """6970 def __init__(self, **kwargs) -> None:71 import warnings7264def _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)8171 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_encoder8277 # 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)83def dumps(obj: t.Any, *, app: Flask | None = None, **kwargs: t.Any) -> str:84 """Serialize data as JSON.8582 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`.8990 :param obj: The data to serialize.91 :param kwargs: Arguments passed to the ``dumps`` implementation.9290def _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.9697 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.99103 # 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)107108109def dumps(obj: t.Any, app: t.Optional["Flask"] = None, **kwargs: t.Any) -> str:110 """Serialize an object to a string of JSON.111112 Takes the same arguments as the built-in :func:`json.dumps`, with113 some defaults from application configuration.114115 :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`.119100 .. versionchanged:: 2.0.2101 :class:`decimal.Decimal` is supported by converting to a string.102103 .. versionchanged:: 2.0124 ``encoding`` is deprecated and will be removed in Flask 2.1.104 ``encoding`` will be removed in Flask 2.1.105106 .. 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 warnings112113 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_app121122 if app:123 return app.json.dumps(obj, **kwargs)124125 kwargs.setdefault("default", _default)126 return _json.dumps(obj, **kwargs)127128129def 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.133139 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`.137142 :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.142143 .. versionchanged:: 2.2144 Calls ``current_app.json.dump``, allowing an app to override145 the behavior.146147 .. versionchanged:: 2.2148 The ``app`` parameter will be removed in Flask 2.3.149150 .. 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 warnings156157 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_app165156def 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)171163 Takes the same arguments as the built-in :func:`json.loads`, with164 some defaults from application configuration.172166 :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`.173def loads(s: str | bytes, *, app: Flask | None = None, **kwargs: t.Any) -> t.Any:174 """Deserialize data as JSON.175176 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`.179180 :param s: Text or UTF-8 bytes.181 :param kwargs: Arguments passed to the ``loads`` implementation.182183 .. versionchanged:: 2.2184 Calls ``current_app.json.loads``, allowing an app to override185 the behavior.186187 .. versionchanged:: 2.2188 The ``app`` parameter will be removed in Flask 2.3.189190 .. 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.193194 .. 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 warnings200201 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_app209210 if app:211 return app.json.loads(s, **kwargs)212213 return _json.loads(s, **kwargs)214215183def 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.216def load(fp: t.IO[t.AnyStr], *, app: Flask | None = None, **kwargs: t.Any) -> t.Any:217 """Deserialize data as JSON read from a file.218186 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`.222189 :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.225226 .. versionchanged:: 2.2227 Calls ``current_app.json.load``, allowing an app to override228 the behavior.229230 .. versionchanged:: 2.2231 The ``app`` parameter will be removed in Flask 2.3.232233 .. 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 warnings239240 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_app248249 if app:250 return app.json.load(fp, **kwargs)251252 return _json.load(fp, **kwargs)253254255def htmlsafe_dumps(obj: t.Any, **kwargs: t.Any) -> str:
7 unmodified lines
263 ``<script>`` tags. The exception is in HTML attributes that are264 double quoted; either use single quotes or the ``|forceescape``265 filter.266267 .. deprecated:: 2.2268 Will be removed in Flask 2.3. This is built-in to Jinja now.269270 .. 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 line
275 Single quotes are escaped, making this safe to use in HTML,276 ``<script>`` tags, and single-quoted attributes without further277 escaping.278 """279 import warnings280281 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)288289290def 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`.294295 .. deprecated:: 2.2296 Will be removed in Flask 2.3.297 """298 import warnings299300 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))307308234def 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.309def 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.314238 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>`.317242 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.320251 .. code-block:: python321 Either positional or keyword arguments can be given, not both.322 If no arguments are given, ``None`` is serialized.323253 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.327255 @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.331263 Will return a JSON response like this:264265 .. code-block:: javascript266267 {268 "username": "admin",269 "email": "admin@localhost",270 "id": 42271 }272273 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.276332 .. versionchanged:: 2.0.2333 :class:`decimal.Decimal` is supported by converting to a string.334335 .. 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`.338339 .. versionadded:: 0.2340 """286 indent = None287 separators = (",", ":")288289 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:290 indent = 2291 separators = (", ", ": ")292293 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 kwargs299300 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
1from __future__ import annotations23import dataclasses4import decimal5import json6import typing as t7import uuid8import weakref9from datetime import date1011from werkzeug.http import http_date1213from ..globals import request1415if t.TYPE_CHECKING: # pragma: no cover16 from ..app import Flask17 from ..wrappers import Response181920class 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.2425 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.2829 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.3233 :param app: An application instance. This will be stored as a34 :class:`weakref.proxy` on the :attr:`_app` attribute.3536 .. versionadded:: 2.237 """3839 def __init__(self, app: Flask) -> None:40 self._app = weakref.proxy(app)4142 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:43 """Serialize data as JSON.4445 :param obj: The data to serialize.46 :param kwargs: May be passed to the underlying JSON library.47 """48 raise NotImplementedError4950 def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:51 """Serialize data as JSON and write to a file.5253 :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))5960 def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:61 """Deserialize data as JSON.6263 :param s: Text or UTF-8 bytes.64 :param kwargs: May be passed to the underlying JSON library.65 """66 raise NotImplementedError6768 def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:69 """Deserialize data as JSON read from a file.7071 :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)7576 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")8182 if not args and not kwargs:83 return None8485 if len(args) == 1:86 return args[0]8788 return args or kwargs8990 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.9495 The :func:`~flask.json.jsonify` function calls this method for96 the current application.9798 Either positional or keyword arguments can be given, not both.99 If no arguments are given, ``None`` is serialized.100101 :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")107108109def _default(o: t.Any) -> t.Any:110 if isinstance(o, date):111 return http_date(o)112113 if isinstance(o, (decimal.Decimal, uuid.UUID)):114 return str(o)115116 if dataclasses and dataclasses.is_dataclass(o):117 return dataclasses.asdict(o)118119 if hasattr(o, "__html__"):120 return str(o.__html__())121122 raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")123124125class DefaultJSONProvider(JSONProvider):126 """Provide JSON operations using Python's built-in :mod:`json`127 library. Serializes the following additional data types:128129 - :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 """138139 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 """146147 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 """152153 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 """159160 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 """165166 mimetype = "application/json"167 """The mimetype set in :meth:`response`."""168169 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:170 """Serialize data as JSON to a string.171172 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.175176 :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 None181182 if bp is not None and bp.json_encoder is not None:183 cls = bp.json_encoder184185 if cls is not None:186 import warnings187188 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)195196 if "default" not in cls.__dict__:197 kwargs.setdefault("default", self.default)198 else:199 kwargs.setdefault("default", self.default)200201 ensure_ascii = self._app.config["JSON_AS_ASCII"]202 sort_keys = self._app.config["JSON_SORT_KEYS"]203204 if ensure_ascii is not None:205 import warnings206207 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_ascii215216 if sort_keys is not None:217 import warnings218219 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_keys227228 kwargs.setdefault("ensure_ascii", ensure_ascii)229 kwargs.setdefault("sort_keys", sort_keys)230 return json.dumps(obj, **kwargs)231232 def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:233 """Deserialize data as JSON from a string or bytes.234235 :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 None240241 if bp is not None and bp.json_decoder is not None:242 cls = bp.json_decoder243244 if cls is not None:245 import warnings246247 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)254255 return json.loads(s, **kwargs)256257 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`.262263 If :attr:`compact` is ``False`` or debug mode is enabled, the264 output will be formatted to be easier to read.265266 Either positional or keyword arguments can be given, not both.267 If no arguments are given, ``None`` is serialized.268269 :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"]277278 if pretty is not None:279 import warnings280281 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.compact290291 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", (",", ":"))295296 if mimetype is not None:297 import warnings298299 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.mimetype307308 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 lines
30from werkzeug.utils import redirect as _wz_redirect31from werkzeug.wrappers import Response as BaseResponse3233from . import cli34from . import json34from . import typing as ft35from .config import Config36from .config import ConfigAttribute37from .ctx import _AppCtxGlobals
10 unmodified lines
48from .helpers import get_env49from .helpers import get_flashed_messages50from .helpers import get_load_dotenv51from .helpers import locked_cached_property53from .json import jsonify52from .json.provider import DefaultJSONProvider53from .json.provider import JSONProvider54from .logging import create_logger55from .scaffold import _endpoint_from_view_func56from .scaffold import _sentinel57from .scaffold import find_package
256 unmodified lines
314 #: 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")317318 #: 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 = None327323 #: 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 = None337338 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.342343 The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses344 Python's built-in :mod:`json` library. A different provider can use345 a different JSON library.346347 .. versionadded:: 2.2348 """349350 #: 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 lines
382 "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 lines
470 #: .. versionadded:: 2.2471 #: Moved from ``flask.abort``, which calls this object.472 self.aborter = self.make_aborter()473474 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.478479 An instance of :attr:`json_provider_class`. Can be customized by480 changing that attribute on a subclass, or by assigning to this481 attribute afterwards.482483 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.486487 .. versionadded:: 2.2488 """489490 #: 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 function
288 unmodified lines
782 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 rv788789 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:790 """Creates the loader for the Jinja2 environment. Can be used to
1172 unmodified lines
1963 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 lines
modified:src/flask/blueprints.py+8 added-2 removed
172 unmodified lines
173 _got_registered_once = False174175 #: 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 = None187188 def __init__(189 self,190 name: str,
457 unmodified lines
modified:src/flask/ctx.py+1 added
305 unmodified lines
306 ) -> 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 lines
modified:src/flask/scaffold.py+8 added-4 removed
4 unmodified lines
5import sys6import typing as t7from collections import defaultdict8from functools import update_wrapper9from json import JSONDecoder10from json import JSONEncoder910from jinja2 import FileSystemLoader11from werkzeug.exceptions import default_exceptions12from werkzeug.exceptions import HTTPException
60 unmodified lines
73 _static_url_path: t.Optional[str] = None7475 #: 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 = None8182 #: 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 = None8889 def __init__(90 self,91 import_name: str,
802 unmodified lines
modified:src/flask/testing.py+2 added-3 removed
10 unmodified lines
11from werkzeug.wrappers import Request as BaseRequest1213from .cli import ScriptInfo14from .globals import _cv_request15from .json import dumps as json_dumps15from .sessions import SessionMixin1617if t.TYPE_CHECKING: # pragma: no cover18 from werkzeug.test import TestResponse
68 unmodified lines
8788 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)929394class FlaskClient(Client):95 """Works like a regular Werkzeug test client but has knowledge about
128 unmodified lines
224 request,225 buffered=buffered,226 follow_redirects=follow_redirects,227 )228 response.json_module = self.application.json # type: ignore[misc]229230 # Re-push contexts that were preserved during the request.231 while self._new_contexts:232 cm = self._new_contexts.pop()
54 unmodified lines
modified:tests/test_basic.py+11 added-22 removed
1300 unmodified lines
1301 assert rv.headers["Content-Type"] == "text/html"1302 assert rv.headers["X-Foo"] == "bar"130313041305def 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])1306def 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 compact13121310 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1311 assert rv.data == compressed_msg131313131314def 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 )13201321 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1322 assert rv.data == pretty_response132313241314def 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 line
1321def test_json_dump_dataclass(app, req_ctx):1322 from dataclasses import make_dataclass13231324 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"}132813291330def 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)133413351336def test_url_generation(app, req_ctx):1337 @app.route("/hello/<name>", methods=["POST"])
621 unmodified lines
modified:tests/test_json.py+17 added-60 removed
6 unmodified lines
7from werkzeug.http import http_date89import flask10from flask import json11from flask.json.provider import DefaultJSONProvider121314@pytest.mark.parametrize("debug", (True, False))15def test_bad_request_debug_message(app, client, debug):
32 unmodified lines
48@pytest.mark.parametrize(49 "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')]50)51def test_json_as_unicode(test_value, expected, app, app_ctx):5152 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 == expected555657def test_json_dump_to_file(app, app_ctx):
111 unmodified lines
169 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) == expected174175176def test_jsonify_uuid_types(app, client):177 """Test jsonify with uuid.UUID types"""
46 unmodified lines
224 class X: # noqa: B903, for Python2 compatibility225 def __init__(self, val):226 self.val = val227228 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)231234 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)233234 class CustomProvider(DefaultJSONProvider):235 def object_hook(self, obj):236 if len(obj) == 1 and "_foo" in obj:237 return X(obj["_foo"])238239 return obj240244 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)244245 app.json = CustomProvider(app)246 app.json.default = default247248 @app.route("/", methods=["POST"])249 def index():250 return flask.json.dumps(flask.request.get_json()["x"])251
4 unmodified lines
256 )257 assert rv.data == b'"<42>"'258259259def test_blueprint_json_customization(app, client):260 class X:261 __slots__ = ("val",)262263 def __init__(self, val):264 self.val = val265266 class MyEncoder(flask.json.JSONEncoder):267 def default(self, o):268 if isinstance(o, X):269 return f"<{o.val}>"270271 return flask.json.JSONEncoder.default(self, o)272273 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)277278 def object_hook(self, obj):279 if len(obj) == 1 and "_foo" in obj:280 return X(obj["_foo"])281282 return obj283284 bp = flask.Blueprint("bp", __name__)285 bp.json_encoder = MyEncoder286 bp.json_decoder = MyDecoder287288 @bp.route("/bp", methods=["POST"])289 def index():290 return flask.json.dumps(flask.request.get_json()["x"])291292 app.register_blueprint(bp)293294 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>"'300301260def _has_encoding(name):261 try:262 import codecs263
23 unmodified lines
287288289def test_json_key_sorting(app, client):290 app.debug = True333334 assert app.config["JSON_SORT_KEYS"]291 assert app.json.sort_keys292 d = dict.fromkeys(range(20), "foo")293294 @app.route("/")295 def index():
70 unmodified lines
modified:tests/test_testing.py+1 added-1 removed
110 unmodified lines
111112113def 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"'118119
284 unmodified lines
modified:CHANGES.rst+15 added
30 unmodified lines
31 - ``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`4041- 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