Skip to content
Myr

update json docs

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 8b5f760 · Browse files · 4 files+140 added−133 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+140 added−133 removed

  • other:+140 added−133 removed

4 files+140 added−133 removed

modified:docs/api.rst+16 added-26 removed
277 unmodified lines
278.. autofunction:: flash279280.. autofunction:: get_flashed_messages281282283JSON Support284------------285286.. module:: flask.json287287Flask uses the built-in :mod:`json` module for the JSON implementation.288It will delegate access to the current application's JSON encoders and289decoders for easier customization.288Flask uses the built-in :mod:`json` module for handling JSON. It will289use the current blueprint's or application's JSON encoder and decoder290for easier customization. By default it handles some extra data types:291291For usage examples, read the :mod:`json` documentation in the standard292library. The following extensions are by default applied to the stdlib's293JSON module:292- :class:`datetime.datetime` and :class:`datetime.date` are serialized293 to :rfc:`822` strings. This is the same as the HTTP date format.294- :class:`uuid.UUID` is serialized to a string.295- :class:`dataclasses.dataclass` is passed to296 :func:`dataclasses.asdict`.297- :class:`~markupsafe.Markup` (or any object with a ``__html__``298 method) will call the ``__html__`` method to get a string.2992951. ``datetime`` objects are serialized as :rfc:`822` strings.2962. Any object with an ``__html__`` method (like :class:`~flask.Markup`)297 will have that method called and then the return value is serialized298 as string.300:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template301filter. The filter marks the output with ``|safe`` so it can be used302inside ``script`` tags.303300The :func:`~htmlsafe_dumps` function of this json module is also available301as a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior302to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use303``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this304happens automatically (but it's harmless to include ``|safe`` anyway).305304.. sourcecode:: html+jinja305306 <script type=text/javascript>309 doSomethingWith({{ user.username|tojson|safe }});307 renderChart({{ axis_data|tojson }});308 </script>309312.. admonition:: Auto-Sort JSON Keys313314 The configuration variable :data:`JSON_SORT_KEYS` can be set to315 ``False`` to stop Flask from auto-sorting keys. By default sorting316 is enabled and outside of the app context sorting is turned on.317318 Notice that disabling key sorting can cause issues when using319 content based HTTP caches and Python's hash randomization feature.320310.. autofunction:: jsonify311312.. autofunction:: dumps313
10 unmodified lines
324 :members:325326.. automodule:: flask.json.tag327328329Template Rendering330------------------331332.. currentmodule:: flask
475 unmodified lines
modified:src/flask/json/__init__.py+117 added-100 removed
17 unmodified lines
18 dataclasses = None192021class JSONEncoder(_json.JSONEncoder):22 """The default Flask JSON encoder. This one extends the default23 encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,24 and ``Markup`` objects.22 """The default JSON encoder. Handles extra types compared to the23 built-in :class:`json.JSONEncoder`.2426 ``datetime`` objects are serialized as RFC 822 datetime strings.27 This is the same as the HTTP date format.25 - :class:`datetime.datetime` and :class:`datetime.date` are26 serialized to :rfc:`822` strings. This is the same as the HTTP27 date format.28 - :class:`uuid.UUID` is serialized to a string.29 - :class:`dataclasses.dataclass` is passed to30 :func:`dataclasses.asdict`.31 - :class:`~markupsafe.Markup` (or any object with a ``__html__``32 method) will call the ``__html__`` method to get a string.3329 In order to support more data types, override the :meth:`default`30 method.34 Assign a subclass of this to :attr:`flask.Flask.json_encoder` or35 :attr:`flask.Blueprint.json_encoder` to override the default.36 """3738 def default(self, o):34 """Implement this method in a subclass such that it returns a35 serializable object for ``o``, or calls the base implementation (to36 raise a :exc:`TypeError`).3738 For example, to support arbitrary iterators, you could implement39 default like this::4041 def default(self, o):42 try:43 iterable = iter(o)44 except TypeError:45 pass46 else:47 return list(iterable)48 return JSONEncoder.default(self, o)39 """Convert ``o`` to a JSON serializable type. See40 :meth:`json.JSONEncoder.default`. Python does not support41 overriding how basic types like ``str`` or ``list`` are42 serialized, they are handled before this method.43 """44 if isinstance(o, datetime):45 return http_date(o.utctimetuple())46 if isinstance(o, date):
7 unmodified lines
54 return super().default(self, o)555657class JSONDecoder(_json.JSONDecoder):64 """The default JSON decoder. This one does not change the behavior from65 the default decoder. Consult the :mod:`json` documentation66 for more information. This decoder is not only used for the load67 functions of this module but also :attr:`~flask.Request`.58 """The default JSON decoder.5960 This does not change any behavior from the built-in61 :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.65 """666768def _dump_arg_defaults(kwargs, app=None):
25 unmodified lines
94 kwargs.setdefault("cls", JSONDecoder)959697def dumps(obj, app=None, **kwargs):101 """Serialize ``obj`` to a JSON-formatted string. If there is an102 app context pushed, use the current app's configured encoder103 (:attr:`~flask.Flask.json_encoder`), or fall back to the default104 :class:`JSONEncoder`.98 """Serialize an object to a string of JSON.99106 Takes the same arguments as the built-in :func:`json.dumps`, and107 does some extra configuration based on the application.100 Takes the same arguments as the built-in :func:`json.dumps`, with101 some defaults from application configuration.102103 :param obj: Object to serialize to JSON.110 :param app: App instance to use to configure the JSON encoder.111 Uses ``current_app`` if not given, and falls back to the default112 encoder when not in an app context.113 :param kwargs: Extra arguments passed to :func:`json.dumps`.104 :param app: Use this app's config instead of the active app context105 or defaults.106 :param kwargs: Extra arguments passed to func:`json.dumps`.107115 .. versionchanged:: 1.0.3108 .. versionchanged:: 2.0109 ``encoding`` is deprecated and will be removed in 2.1.110111 .. versionchanged:: 1.0.3112 ``app`` can be passed directly, rather than requiring an app113 context for configuration.114 """115 _dump_arg_defaults(kwargs, app=app)
13 unmodified lines
129 return rv130131132def dump(obj, fp, app=None, **kwargs):138 """Like :func:`dumps` but writes into a file object."""133 """Serialize an object to JSON written to a file object.134135 Takes the same arguments as the built-in :func:`json.dump`, with136 some defaults from application configuration.137138 :param obj: Object to serialize to JSON.139 :param fp: File object to write JSON to.140 :param app: Use this app's config instead of the active app context141 or defaults.142 :param kwargs: Extra arguments passed to func:`json.dump`.143144 .. versionchanged:: 2.0145 Writing to a binary file, and the ``encoding`` argument, is146 deprecated and will be removed in 2.1.147 """148 _dump_arg_defaults(kwargs, app=app)149 encoding = kwargs.pop("encoding", None)150 show_warning = encoding is not None151
14 unmodified lines
166 _json.dump(obj, fp, **kwargs)167168169def loads(s, app=None, **kwargs):161 """Deserialize an object from a JSON-formatted string ``s``. If162 there is an app context pushed, use the current app's configured163 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the164 default :class:`JSONDecoder`.170 """Deserialize an object from a string of JSON.171166 Takes the same arguments as the built-in :func:`json.loads`, and167 does some extra configuration based on the application.172 Takes the same arguments as the built-in :func:`json.loads`, with173 some defaults from application configuration.174175 :param s: JSON string to deserialize.170 :param app: App instance to use to configure the JSON decoder.171 Uses ``current_app`` if not given, and falls back to the default172 encoder when not in an app context.173 :param kwargs: Extra arguments passed to :func:`json.dumps`.176 :param app: Use this app's config instead of the active app context177 or defaults.178 :param kwargs: Extra arguments passed to func:`json.dump`.179175 .. versionchanged:: 1.0.3180 .. versionchanged:: 2.0181 ``encoding`` is deprecated and will be removed in 2.1. The data182 must be a string or UTF-8 bytes.183184 .. versionchanged:: 1.0.3185 ``app`` can be passed directly, rather than requiring an app186 context for configuration.187 """188 _load_arg_defaults(kwargs, app=app)
13 unmodified lines
202 return _json.loads(s, **kwargs)203204205def load(fp, app=None, **kwargs):198 """Like :func:`loads` but reads from a file object."""206 """Deserialize an object from JSON read from a file object.207208 Takes the same arguments as the built-in :func:`json.load`, with209 some defaults from application configuration.210211 :param fp: File object to read JSON from.212 :param app: Use this app's config instead of the active app context213 or defaults.214 :param kwargs: Extra arguments passed to func:`json.load`.215216 .. versionchanged:: 2.0217 ``encoding`` is deprecated and will be removed in 2.1. The file218 must be text mode, or binary mode with UTF-8 bytes.219 """220 _load_arg_defaults(kwargs, app=app)221 encoding = kwargs.pop("encoding", None)222223 if encoding is not None:
15 unmodified lines
239)240241242def htmlsafe_dumps(obj, **kwargs):222 """Works exactly like :func:`dumps` but is safe for use in ``<script>``223 tags. It accepts the same arguments and returns a JSON string. Note that224 this is available in templates through the ``|tojson`` filter which will225 also mark the result as safe. Due to how this function escapes certain226 characters this is safe even if used outside of ``<script>`` tags.243 """Serialize an object to a string of JSON, replacing HTML-unsafe244 characters with Unicode escapes. Otherwise behaves the same as245 :func:`dumps`.246228 The following characters are escaped in strings:247 This is available in templates as the ``|tojson`` filter, which will248 also mark the result with ``|safe``.249230 - ``<``231 - ``>``232 - ``&``233 - ``'``250 The returned string is safe to render in HTML documents and251 ``<script>`` tags. The exception is in HTML attributes that are252 double quoted; either use single quotes or the ``|forceescape``253 filter.254235 This makes it safe to embed such strings in any place in HTML with the236 notable exception of double quoted attributes. In that case single237 quote your attributes or HTML escape it in addition.238255 .. versionchanged:: 0.10240 This function's return value is now always safe for HTML usage, even241 if outside of script tags or if used in XHTML. This rule does not242 hold true when using this function in HTML attributes that are double243 quoted. Always single quote attributes if you use the ``|tojson``244 filter. Alternatively use ``|tojson|forceescape``.256 Single quotes are escaped, making this safe to use in HTML,257 ``<script>`` tags, and single-quoted attributes without further258 escaping.259 """260 return dumps(obj, **kwargs).translate(_htmlsafe_map)261262263def htmlsafe_dump(obj, fp, **kwargs):250 """Like :func:`htmlsafe_dumps` but writes into a file object."""264 """Serialize an object to JSON written to a file object, replacing265 HTML-unsafe characters with Unicode escapes. See266 :func:`htmlsafe_dumps` and :func:`dumps`.267 """268 fp.write(htmlsafe_dumps(obj, **kwargs))269270271def jsonify(*args, **kwargs):255 """This function wraps :func:`dumps` to add a few enhancements that make256 life easier. It turns the JSON output into a :class:`~flask.Response`257 object with the :mimetype:`application/json` mimetype. For convenience, it258 also converts multiple arguments into an array or multiple keyword arguments259 into a dict. This means that both ``jsonify(1,2,3)`` and260 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.272 """Serialize data to JSON and wrap it in a :class:`~flask.Response`273 with the :mimetype:`application/json` mimetype.274262 For clarity, the JSON serialization behavior has the following differences263 from :func:`dumps`:275 Uses :func:`dumps` to serialize the data, but ``args`` and276 ``kwargs`` are treated as data rather than arguments to277 :func:`json.dumps`.278265 1. Single argument: Passed straight through to :func:`dumps`.266 2. Multiple arguments: Converted to an array before being passed to267 :func:`dumps`.268 3. Multiple keyword arguments: Converted to a dict before being passed to269 :func:`dumps`.270 4. Both args and kwargs: Behavior undefined and will throw an exception.279 1. Single argument: Treated as a single value.280 2. Multiple arguments: Treated as a list of values.281 ``jsonify(1, 2, 3)`` is the same as ``jsonify([1, 2, 3])``.282 3. Keyword arguments: Treated as a dict of values.283 ``jsonify(data=data, errors=errors)`` is the same as284 ``jsonify({"data": data, "errors": errors})``.285 4. Passing both arguments and keyword arguments is not allowed as286 it's not clear what should happen.287272 Example usage::288 .. code-block:: python289290 from flask import jsonify291276 @app.route('/_get_current_user')292 @app.route("/users/me")293 def get_current_user():294 return jsonify(278 return jsonify(username=g.user.username,279 email=g.user.email,280 id=g.user.id)295 username=g.user.username,296 email=g.user.email,297 id=g.user.id,298 )299282 This will send a JSON response like this to the browser::300 Will return a JSON response like this:301302 .. code-block:: javascript303304 {285 "username": "admin",286 "email": "admin@localhost",287 "id": 42305 "username": "admin",306 "email": "admin@localhost",307 "id": 42308 }309310 The default output omits indents and spaces after separators. In311 debug mode or if :data:`JSONIFY_PRETTYPRINT_REGULAR` is ``True``,312 the output will be formatted to be easier to read.313314 .. versionchanged:: 0.11315 Added support for serializing top-level arrays. This introduces293 a security risk in ancient browsers. See :ref:`security-json`294 for details.316 a security risk in ancient browsers. See :ref:`security-json`.317296 This function's response will be pretty printed if the297 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the298 Flask app is running in debug mode. Compressed (not pretty) formatting299 currently means no indents and no spaces after separators.300318 .. versionadded:: 0.2319 """320 indent = None321 separators = (",", ":")
20 unmodified lines
modified:src/flask/json/tag.py+4 added-4 removed
43 unmodified lines
44from base64 import b64encode45from datetime import datetime46from uuid import UUID4748from jinja2 import Markup48from markupsafe import Markup49from werkzeug.http import http_date50from werkzeug.http import parse_date5152from ..json import dumps
113 unmodified lines
166 return b64decode(value)167168169class TagMarkup(JSONTag):170 """Serialize anything matching the :class:`~flask.Markup` API by170 """Serialize anything matching the :class:`~markupsafe.Markup` API by171 having a ``__html__`` method to the result of that method. Always172 deserializes to an instance of :class:`~flask.Markup`."""172 deserializes to an instance of :class:`~markupsafe.Markup`."""173174 __slots__ = ()175 key = " m"176
44 unmodified lines
221222 * :class:`dict`223 * :class:`tuple`224 * :class:`bytes`225 * :class:`~flask.Markup`225 * :class:`~markupsafe.Markup`226 * :class:`~uuid.UUID`227 * :class:`~datetime.datetime`228 """229
77 unmodified lines
modified:CHANGES.rst+3 added-3 removed
4 unmodified lines
56Unreleased78- Drop support for Python 2 and 3.5.9- JSON support no longer uses simplejson. To use another JSON module,10 override ``app.json_encoder`` and ``json_decoder``. :issue:`3555`11- The ``encoding`` option to JSON functions is deprecated. :pr:`3562`12- Add :meth:`sessions.SessionInterface.get_cookie_name` to allow13 setting the session cookie name dynamically. :pr:`3369`14- Add :meth:`Config.from_file` to load config using arbitrary file15 loaders, such as ``toml.load`` or ``json.load``.
5 unmodified lines
21 :mod:`io` object in text mode. Previously, it would respond with22 200 OK and an empty file. :issue:`3358`23- When using ad-hoc certificates, check for the cryptography library24 instead of PyOpenSSL. :pr:`3492`22- JSON support no longer uses simplejson if it's installed. To use23 another JSON module, override ``app.json_encoder`` and24 ``json_decoder``. :issue:`3555`252627Version 1.1.228-------------
1011 unmodified lines