remove simplejson
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- remove encoding detection backport, json.loads supports it directly - use str.translate instead of multiple str.replace
authored by David Lord · committed by David Lord · parent 024f0d3 · Browse files · 6 files·+27 added−113 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+27 added−113 removed
- tests:+0 added−21 removed
- other:+27 added−92 removed
Provenance
- Commit
c43edfc- Tree
885ebb0- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
024f0d3
6 files changed+27 added−113 removed
modified:docs/api.rst+3 added-16 removed
282 unmodified lines283 ------------284 285 .. module:: flask.json286 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.287+Flask uses the built-in :mod:`json` module for the JSON implementation.288+It will delegate access to the current application's JSON encoders and289+decoders for easier customization.290 293-So for starters instead of doing::294-295- try:296- import simplejson as json297- except ImportError:298- import json299-300-You can instead just do this::301-302- from flask import json303-291 For usage examples, read the :mod:`json` documentation in the standard292 library. The following extensions are by default applied to the stdlib's293 JSON module:294 523 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+20 added-69 removed
1-import codecs1 import io2+import json as _json3 import uuid4 from datetime import date5 from datetime import datetime6 7-from itsdangerous import json as _json7 from jinja2 import Markup8 from werkzeug.http import http_date9 10 from ..globals import current_app4 unmodified lines15 except ImportError:16 # Python < 3.717 dataclasses = None18 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("/")19 24-20 __all__ = [21 "dump",22 "dumps",23 "load",63 unmodified lines87 88 89 class JSONDecoder(_json.JSONDecoder):90 """The default JSON decoder. This one does not change the behavior from96- the default simplejson decoder. Consult the :mod:`json` documentation91+ the default decoder. Consult the :mod:`json` documentation92 for more information. This decoder is not only used for the load93 functions of this module but also :attr:`~flask.Request`.94 """95 31 unmodified lines127 else:128 kwargs.setdefault("cls", JSONDecoder)129 130 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-131 def dumps(obj, app=None, **kwargs):132 """Serialize ``obj`` to a JSON-formatted string. If there is an133 app context pushed, use the current app's configured encoder134 (:attr:`~flask.Flask.json_encoder`), or fall back to the default135 :class:`JSONEncoder`.136 137 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.138+ does some extra configuration based on the application.139 140 :param obj: Object to serialize to JSON.141 :param app: App instance to use to configure the JSON encoder.142 Uses ``current_app`` if not given, and falls back to the default7 unmodified lines150 """151 _dump_arg_defaults(kwargs, app=app)152 encoding = kwargs.pop("encoding", None)153 rv = _json.dumps(obj, **kwargs)154+155 if encoding is not None and isinstance(rv, str):156 rv = rv.encode(encoding)157+158 return rv159 160 161 def dump(obj, fp, app=None, **kwargs):162 """Like :func:`dumps` but writes into a file object."""163 _dump_arg_defaults(kwargs, app=app)164 encoding = kwargs.pop("encoding", None)165+166 if encoding is not None:167 fp = _wrap_writer_for_text(fp, encoding)168+169 _json.dump(obj, fp, **kwargs)170 171 172 def loads(s, app=None, **kwargs):2 unmodified lines175 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the176 default :class:`JSONDecoder`.177 178 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.179+ does some extra configuration based on the application.180 181 :param s: JSON string to deserialize.182 :param app: App instance to use to configure the JSON decoder.183 Uses ``current_app`` if not given, and falls back to the default5 unmodified lines189 ``app`` can be passed directly, rather than requiring an app190 context for configuration.191 """192 _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)193+ encoding = kwargs.pop("encoding", None)194+195+ if encoding is not None and isinstance(s, bytes):196 s = s.decode(encoding)197+198 return _json.loads(s, **kwargs)199 200 201 def load(fp, app=None, **kwargs):202 """Like :func:`loads` but reads from a file object."""203 _load_arg_defaults(kwargs, app=app)204+ encoding = kwargs.pop("encoding", None)250- fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")205+ fp = _wrap_reader_for_text(fp, encoding or "utf-8")206 return _json.load(fp, **kwargs)207 208 209+_htmlsafe_map = str.maketrans(210+ {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026", "'": "\\u0027"}211+)212+213+214 def htmlsafe_dumps(obj, **kwargs):215 """Works exactly like :func:`dumps` but is safe for use in ``<script>``216 tags. It accepts the same arguments and returns a JSON string. Note that217 this is available in templates through the ``|tojson`` filter which will17 unmodified lines235 hold true when using this function in HTML attributes that are double236 quoted. Always single quote attributes if you use the ``|tojson``237 filter. Alternatively use ``|tojson|forceescape``.238 """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 rv239+ return dumps(obj, **kwargs).translate(_htmlsafe_map)240 241 242 def htmlsafe_dump(obj, fp, **kwargs):243 """Like :func:`htmlsafe_dumps` but writes into a file object."""75 unmodified linesmodified:tests/test_helpers.py-21 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"] = False932 unmodified linesmodified:CHANGES.rst+3 added
17 unmodified lines18 :mod:`io` object in text mode. Previously, it would respond with19 200 OK and an empty file. :issue:`3358`20 - When using ad-hoc certificates, check for the cryptography library21 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`25 26 27 Version 1.1.228 -------------1011 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