Merge pull request #3562 from pallets/remove-simplejson
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Remove simplejson and deprecate encoding options
authored by David Lord · committed by GitHub · parents 024f0d3, 756902c · Browse files · 7 files·+210 added−284 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+210 added−284 removed
- tests:+0 added−22 removed
- other:+210 added−262 removed
Provenance
- Commit
e69b49b- Tree
6ea002a- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
024f0d3- Parent 2
756902c
7 files changed+210 added−284 removed
modified:docs/api.rst+16 added-39 removed
277 unmodified lines278 .. autofunction:: flash279 280 .. autofunction:: get_flashed_messages281 282+283 JSON Support284 ------------285 286 .. module:: flask.json287 287-Flask uses ``simplejson`` for the JSON implementation. Since simplejson288-is provided by both the standard library as well as extension, Flask will289-try simplejson first and then fall back to the stdlib json module. On top290-of that it will delegate access to the current application's JSON encoders291-and decoders for easier customization.288+Flask uses the built-in :mod:`json` module for handling JSON. It will289+use the current blueprint's or application's JSON encoder and decoder290+for easier customization. By default it handles some extra data types:291 293-So for starters instead of doing::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.299 295- try:296- import simplejson as json297- except ImportError:298- import json300+:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template301+filter. The filter marks the output with ``|safe`` so it can be used302+inside ``script`` tags.303 300-You can instead just do this::301-302- from flask import json303-304-For usage examples, read the :mod:`json` documentation in the standard305-library. The following extensions are by default applied to the stdlib's306-JSON module:307-308-1. ``datetime`` objects are serialized as :rfc:`822` strings.309-2. Any object with an ``__html__`` method (like :class:`~flask.Markup`)310- will have that method called and then the return value is serialized311- as string.312-313-The :func:`~htmlsafe_dumps` function of this json module is also available314-as a filter called ``|tojson`` in Jinja2. Note that in versions of Flask prior315-to Flask 0.10, you must disable escaping with ``|safe`` if you intend to use316-``|tojson`` output inside ``script`` tags. In Flask 0.10 and above, this317-happens automatically (but it's harmless to include ``|safe`` anyway).318-304 .. sourcecode:: html+jinja305 306 <script type=text/javascript>322- doSomethingWith({{ user.username|tojson|safe }});307+ renderChart({{ axis_data|tojson }});308 </script>309 325-.. admonition:: Auto-Sort JSON Keys326-327- The configuration variable :data:`JSON_SORT_KEYS` can be set to328- ``False`` to stop Flask from auto-sorting keys. By default sorting329- is enabled and outside of the app context sorting is turned on.330-331- Notice that disabling key sorting can cause issues when using332- content based HTTP caches and Python's hash randomization feature.333-310 .. autofunction:: jsonify311 312 .. autofunction:: dumps313 10 unmodified lines324 :members:325 326 .. automodule:: flask.json.tag327 328+329 Template Rendering330 ------------------331 332 .. currentmodule:: flask475 unmodified linesmodified:docs/installation.rst-4 removed
37 unmodified lines38 These distributions will not be installed automatically. Flask will detect and39 use them if you install them.40 41 * `Blinker`_ provides support for :doc:`signals`.42-* `SimpleJSON`_ is a fast JSON implementation that is compatible with43- Python's ``json`` module. It is preferred for JSON operations if it is44- installed.42 * `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``43 commands.44 * `Watchdog`_ provides a faster, more efficient reloader for the development45 server.46 47 .. _Blinker: https://pythonhosted.org/blinker/51-.. _SimpleJSON: https://simplejson.readthedocs.io/48 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme49 .. _watchdog: https://pythonhosted.org/watchdog/50 51 72 unmodified linesmodified:src/flask/json/__init__.py+186 added-212 removed
1-import codecs1 import io2+import json as _json3 import uuid4+import warnings5 from datetime import date6 from datetime import datetime7 7-from itsdangerous import json as _json8-from jinja2 import Markup8+from markupsafe import Markup9 from werkzeug.http import http_date10 11 from ..globals import current_app12 from ..globals import request3 unmodified lines16 except ImportError:17 # Python < 3.718 dataclasses = None19 20-# Figure out if simplejson escapes slashes. This behavior was changed21-# from one version to another without reason.22-_slash_escape = "\\/" not in _json.dumps("/")20 24-25-__all__ = [26- "dump",27- "dumps",28- "load",29- "loads",30- "htmlsafe_dump",31- "htmlsafe_dumps",32- "JSONDecoder",33- "JSONEncoder",34- "jsonify",35-]36-37-38-def _wrap_reader_for_text(fp, encoding):39- if isinstance(fp.read(0), bytes):40- fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)41- return fp42-43-44-def _wrap_writer_for_text(fp, encoding):45- try:46- fp.write("")47- except TypeError:48- fp = io.TextIOWrapper(fp, encoding)49- return fp50-51-21 class JSONEncoder(_json.JSONEncoder):53- """The default Flask JSON encoder. This one extends the default54- encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,55- and ``Markup`` objects.22+ """The default JSON encoder. Handles extra types compared to the23+ built-in :class:`json.JSONEncoder`.24 57- ``datetime`` objects are serialized as RFC 822 datetime strings.58- 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.33 60- In order to support more data types, override the :meth:`default`61- method.34+ Assign a subclass of this to :attr:`flask.Flask.json_encoder` or35+ :attr:`flask.Blueprint.json_encoder` to override the default.36 """37 38 def default(self, o):65- """Implement this method in a subclass such that it returns a66- serializable object for ``o``, or calls the base implementation (to67- raise a :exc:`TypeError`).68-69- For example, to support arbitrary iterators, you could implement70- default like this::71-72- def default(self, o):73- try:74- iterable = iter(o)75- except TypeError:76- pass77- else:78- return list(iterable)79- 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):3 unmodified lines50 if dataclasses and dataclasses.is_dataclass(o):51 return dataclasses.asdict(o)52 if hasattr(o, "__html__"):53 return str(o.__html__())91- return _json.JSONEncoder.default(self, o)54+ return super().default(self, o)55 56 57 class JSONDecoder(_json.JSONDecoder):95- """The default JSON decoder. This one does not change the behavior from96- the default simplejson decoder. Consult the :mod:`json` documentation97- for more information. This decoder is not only used for the load98- functions of this module but also :attr:`~flask.Request`.58+ """The default JSON decoder.59+60+ This does not change any behavior from the built-in61+ :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 67 68 def _dump_arg_defaults(kwargs, app=None):2 unmodified lines71 app = current_app72 73 if app:74 bp = app.blueprints.get(request.blueprint) if request else None109- kwargs.setdefault(110- "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder111- )112-113- if not app.config["JSON_AS_ASCII"]:114- kwargs.setdefault("ensure_ascii", False)115-75+ cls = bp.json_encoder if bp and bp.json_encoder else app.json_encoder76+ kwargs.setdefault("cls", cls)77+ kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])78 kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])79 else:80 kwargs.setdefault("sort_keys", True)81 kwargs.setdefault("cls", JSONEncoder)5 unmodified lines87 app = current_app88 89 if app:90 bp = app.blueprints.get(request.blueprint) if request else None129- kwargs.setdefault(130- "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder131- )91+ cls = bp.json_decoder if bp and bp.json_decoder else app.json_decoder92+ kwargs.setdefault("cls", cls)93 else:94 kwargs.setdefault("cls", JSONDecoder)95 96 136-def detect_encoding(data):137- """Detect which UTF codec was used to encode the given bytes.138-139- The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is140- accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big141- or little endian. Some editors or libraries may prepend a BOM.142-143- :param data: Bytes in unknown UTF encoding.144- :return: UTF encoding name145- """146- head = data[:4]147-148- if head[:3] == codecs.BOM_UTF8:149- return "utf-8-sig"150-151- if b"\x00" not in head:152- return "utf-8"153-154- if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):155- return "utf-32"156-157- if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):158- return "utf-16"159-160- if len(head) == 4:161- if head[:3] == b"\x00\x00\x00":162- return "utf-32-be"163-164- if head[::2] == b"\x00\x00":165- return "utf-16-be"166-167- if head[1:] == b"\x00\x00\x00":168- return "utf-32-le"169-170- if head[1::2] == b"\x00\x00":171- return "utf-16-le"172-173- if len(head) == 2:174- return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"175-176- return "utf-8"177-178-97 def dumps(obj, app=None, **kwargs):180- """Serialize ``obj`` to a JSON-formatted string. If there is an181- app context pushed, use the current app's configured encoder182- (:attr:`~flask.Flask.json_encoder`), or fall back to the default183- :class:`JSONEncoder`.98+ """Serialize an object to a string of JSON.99 185- Takes the same arguments as the built-in :func:`json.dumps`, and186- does some extra configuration based on the application. If the187- simplejson package is installed, it is preferred.100+ Takes the same arguments as the built-in :func:`json.dumps`, with101+ some defaults from application configuration.102 103 :param obj: Object to serialize to JSON.190- :param app: App instance to use to configure the JSON encoder.191- Uses ``current_app`` if not given, and falls back to the default192- encoder when not in an app context.193- :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`.107 195- .. versionchanged:: 1.0.3108+ .. versionchanged:: 2.0109+ ``encoding`` is deprecated and will be removed in 2.1.110 111+ .. 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)116 encoding = kwargs.pop("encoding", None)117 rv = _json.dumps(obj, **kwargs)118+119+ if encoding is not None:120+ warnings.warn(121+ "'encoding' is deprecated and will be removed in 2.1.",122+ DeprecationWarning,123+ stacklevel=2,124+ )125+203- if encoding is not None and isinstance(rv, str):204- rv = rv.encode(encoding)126+ if isinstance(rv, str):127+ return rv.encode(encoding)128+129 return rv130 131 132 def dump(obj, fp, app=None, **kwargs):209- """Like :func:`dumps` but writes into a file object."""133+ """Serialize an object to JSON written to a file object.134+135+ Takes the same arguments as the built-in :func:`json.dump`, with136+ some defaults from application configuration.137+138+ :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`.143+144+ .. 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)212- if encoding is not None:213- fp = _wrap_writer_for_text(fp, encoding)150+ show_warning = encoding is not None151+152+ try:153+ fp.write("")154+ except TypeError:155+ show_warning = True156+ fp = io.TextIOWrapper(fp, encoding or "utf-8")157+158+ if show_warning:159+ warnings.warn(160+ "Writing to a binary file, and the 'encoding' argument, is"161+ " deprecated and will be removed in 2.1.",162+ DeprecationWarning,163+ stacklevel=2,164+ )165+166 _json.dump(obj, fp, **kwargs)167 168 169 def loads(s, app=None, **kwargs):218- """Deserialize an object from a JSON-formatted string ``s``. If219- there is an app context pushed, use the current app's configured220- decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the221- default :class:`JSONDecoder`.170+ """Deserialize an object from a string of JSON.171 223- Takes the same arguments as the built-in :func:`json.loads`, and224- does some extra configuration based on the application. If the225- simplejson package is installed, it is preferred.172+ Takes the same arguments as the built-in :func:`json.loads`, with173+ some defaults from application configuration.174 175 :param s: JSON string to deserialize.228- :param app: App instance to use to configure the JSON decoder.229- Uses ``current_app`` if not given, and falls back to the default230- encoder when not in an app context.231- :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`.179 233- .. 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.183 184+ .. 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)239- if isinstance(s, bytes):240- encoding = kwargs.pop("encoding", None)241- if encoding is None:242- encoding = detect_encoding(s)243- s = s.decode(encoding)189+ encoding = kwargs.pop("encoding", None)190+191+ if encoding is not None:192+ warnings.warn(193+ "'encoding' is deprecated and will be removed in 2.1. The"194+ " data must be a string or UTF-8 bytes.",195+ DeprecationWarning,196+ stacklevel=2,197+ )198+199+ if isinstance(s, bytes):200+ s = s.decode(encoding)201+202 return _json.loads(s, **kwargs)203 204 205 def load(fp, app=None, **kwargs):248- """Like :func:`loads` but reads from a file object."""206+ """Deserialize an object from JSON read from a file object.207+208+ Takes the same arguments as the built-in :func:`json.load`, with209+ some defaults from application configuration.210+211+ :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`.215+216+ .. 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)250- fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")221+ encoding = kwargs.pop("encoding", None)222+223+ if encoding is not None:224+ warnings.warn(225+ "'encoding' is deprecated and will be removed in 2.1. The"226+ " file must be text mode, or binary mode with UTF-8 bytes.",227+ DeprecationWarning,228+ stacklevel=2,229+ )230+231+ if isinstance(fp.read(0), bytes):232+ fp = io.TextIOWrapper(fp, encoding)233+234 return _json.load(fp, **kwargs)235 236 254-def htmlsafe_dumps(obj, **kwargs):255- """Works exactly like :func:`dumps` but is safe for use in ``<script>``256- tags. It accepts the same arguments and returns a JSON string. Note that257- this is available in templates through the ``|tojson`` filter which will258- also mark the result as safe. Due to how this function escapes certain259- characters this is safe even if used outside of ``<script>`` tags.237+_htmlsafe_map = str.maketrans(238+ {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026", "'": "\\u0027"}239+)240 261- The following characters are escaped in strings:241 263- - ``<``264- - ``>``265- - ``&``266- - ``'``242+def htmlsafe_dumps(obj, **kwargs):243+ """Serialize an object to a string of JSON, replacing HTML-unsafe244+ characters with Unicode escapes. Otherwise behaves the same as245+ :func:`dumps`.246 268- This makes it safe to embed such strings in any place in HTML with the269- notable exception of double quoted attributes. In that case single270- quote your attributes or HTML escape it in addition.247+ This is available in templates as the ``|tojson`` filter, which will248+ also mark the result with ``|safe``.249 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.254+255 .. versionchanged:: 0.10273- This function's return value is now always safe for HTML usage, even274- if outside of script tags or if used in XHTML. This rule does not275- hold true when using this function in HTML attributes that are double276- quoted. Always single quote attributes if you use the ``|tojson``277- 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 """279- rv = (280- dumps(obj, **kwargs)281- .replace("<", "\\u003c")282- .replace(">", "\\u003e")283- .replace("&", "\\u0026")284- .replace("'", "\\u0027")285- )286- if not _slash_escape:287- rv = rv.replace("\\/", "/")288- return rv260+ return dumps(obj, **kwargs).translate(_htmlsafe_map)261 262 263 def htmlsafe_dump(obj, fp, **kwargs):292- """Like :func:`htmlsafe_dumps` but writes into a file object."""293- fp.write(str(htmlsafe_dumps(obj, **kwargs)))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))269 270 271 def jsonify(*args, **kwargs):297- """This function wraps :func:`dumps` to add a few enhancements that make298- life easier. It turns the JSON output into a :class:`~flask.Response`299- object with the :mimetype:`application/json` mimetype. For convenience, it300- also converts multiple arguments into an array or multiple keyword arguments301- into a dict. This means that both ``jsonify(1,2,3)`` and302- ``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.274 304- For clarity, the JSON serialization behavior has the following differences305- 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`.278 307- 1. Single argument: Passed straight through to :func:`dumps`.308- 2. Multiple arguments: Converted to an array before being passed to309- :func:`dumps`.310- 3. Multiple keyword arguments: Converted to a dict before being passed to311- :func:`dumps`.312- 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.287 314- Example usage::288+ .. code-block:: python289 290 from flask import jsonify291 318- @app.route('/_get_current_user')292+ @app.route("/users/me")293 def get_current_user():294+ return jsonify(320- return jsonify(username=g.user.username,321- email=g.user.email,322- id=g.user.id)295+ username=g.user.username,296+ email=g.user.email,297+ id=g.user.id,298+ )299 324- This will send a JSON response like this to the browser::300+ Will return a JSON response like this:301 302+ .. code-block:: javascript303+304 {327- "username": "admin",328- "email": "admin@localhost",329- "id": 42305+ "username": "admin",306+ "email": "admin@localhost",307+ "id": 42308 }309 310+ 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.313 314 .. versionchanged:: 0.11315 Added support for serializing top-level arrays. This introduces335- a security risk in ancient browsers. See :ref:`security-json`336- for details.316+ a security risk in ancient browsers. See :ref:`security-json`.317 338- This function's response will be pretty printed if the339- ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the340- Flask app is running in debug mode. Compressed (not pretty) formatting341- currently means no indents and no spaces after separators.342-318 .. versionadded:: 0.2319 """345-320 indent = None321 separators = (",", ":")322 323 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:18 unmodified linesmodified:src/flask/json/tag.py+4 added-4 removed
43 unmodified lines44 from base64 import b64encode45 from datetime import datetime46 from uuid import UUID47 48-from jinja2 import Markup48+from markupsafe import Markup49 from werkzeug.http import http_date50 from werkzeug.http import parse_date51 52 from ..json import dumps113 unmodified lines166 return b64decode(value)167 168 169 class 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`."""173 174 __slots__ = ()175 key = " m"176 44 unmodified lines221 222 * :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 linesmodified:tests/test_helpers.py-22 removed
11 unmodified lines12 from werkzeug.http import parse_cache_control_header13 from werkzeug.http import parse_options_header14 15 import flask16-from flask import json16 from flask.helpers import get_debug_flag17 from flask.helpers import get_env18 19 42 unmodified lines62 return datetime.timedelta()63 64 65 class TestJSON:67- @pytest.mark.parametrize(68- "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": "🐍"})69- )70- @pytest.mark.parametrize(71- "encoding",72- (73- "utf-8",74- "utf-8-sig",75- "utf-16-le",76- "utf-16-be",77- "utf-16",78- "utf-32-le",79- "utf-32-be",80- "utf-32",81- ),82- )83- def test_detect_encoding(self, value, encoding):84- data = json.dumps(value).encode(encoding)85- assert json.loads(data) == value86-66 @pytest.mark.parametrize("debug", (True, False))67 def test_bad_request_debug_message(self, app, client, debug):68 app.config["DEBUG"] = debug69 app.config["TRAP_BAD_REQUEST_ERRORS"] = False161 unmodified lines231 def test_template_escaping(self, app, req_ctx):232 render = flask.render_template_string233 rv = flask.json.htmlsafe_dumps("</script>")234 assert rv == '"\\u003c/script\\u003e"'256- assert type(rv) is str235 rv = render('{{ "</script>"|tojson }}')236 assert rv == '"\\u003c/script\\u003e"'237 rv = render('{{ "<\0/script>"|tojson }}')238 assert rv == '"\\u003c\\u0000/script\\u003e"'762 unmodified linesmodified:CHANGES.rst+3 added
4 unmodified lines5 6 Unreleased7 8 - 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``.1024 unmodified linesmodified:tox.ini+1 added-3 removed
1 [tox]2 envlist =3 py{38,37,36,py3}4- py38-{simplejson,devel,lowest}4+ py38-{devel,lowest}5 style6 docs7 skip_missing_interpreters = true8 14 unmodified lines23 devel: https://github.com/pallets/jinja/archive/master.tar.gz24 devel: https://github.com/pallets/itsdangerous/archive/master.tar.gz25 devel: https://github.com/pallets/click/archive/master.tar.gz26 27- simplejson: simplejson28-27 commands =28 pip install -q -e examples/tutorial[test]29 pip install -q -e examples/javascript[test]30 10 unmodified lines