Skip to content
Myr

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

6 files+27 added−113 removed

modified:docs/api.rst+3 added-16 removed
282 unmodified lines
283------------284285.. module:: flask.json286287Flask uses ``simplejson`` for the JSON implementation. Since simplejson288is provided by both the standard library as well as extension, Flask will289try simplejson first and then fall back to the stdlib json module. On top290of that it will delegate access to the current application's JSON encoders291and decoders for easier customization.287Flask 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.290293So for starters instead of doing::294295 try:296 import simplejson as json297 except ImportError:298 import json299300You can instead just do this::301302 from flask import json303291For usage examples, read the :mod:`json` documentation in the standard292library. The following extensions are by default applied to the stdlib's293JSON module:294
523 unmodified lines
modified:docs/installation.rst-4 removed
37 unmodified lines
38These distributions will not be installed automatically. Flask will detect and39use them if you install them.4041* `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.4647.. _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/5051
72 unmodified lines
modified:src/flask/json/__init__.py+20 added-69 removed
1import codecs1import io2import json as _json3import uuid4from datetime import date5from datetime import datetime67from itsdangerous import json as _json7from jinja2 import Markup8from werkzeug.http import http_date910from ..globals import current_app
4 unmodified lines
15except ImportError:16 # Python < 3.717 dataclasses = None1820# Figure out if simplejson escapes slashes. This behavior was changed21# from one version to another without reason.22_slash_escape = "\\/" not in _json.dumps("/")192420__all__ = [21 "dump",22 "dumps",23 "load",
63 unmodified lines
878889class 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 lines
127 else:128 kwargs.setdefault("cls", JSONDecoder)129130136def detect_encoding(data):137 """Detect which UTF codec was used to encode the given bytes.138139 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.142143 :param data: Bytes in unknown UTF encoding.144 :return: UTF encoding name145 """146 head = data[:4]147148 if head[:3] == codecs.BOM_UTF8:149 return "utf-8-sig"150151 if b"\x00" not in head:152 return "utf-8"153154 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):155 return "utf-32"156157 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):158 return "utf-16"159160 if len(head) == 4:161 if head[:3] == b"\x00\x00\x00":162 return "utf-32-be"163164 if head[::2] == b"\x00\x00":165 return "utf-16-be"166167 if head[1:] == b"\x00\x00\x00":168 return "utf-32-le"169170 if head[1::2] == b"\x00\x00":171 return "utf-16-le"172173 if len(head) == 2:174 return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"175176 return "utf-8"177178131def 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`.136137 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.139140 :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 default
7 unmodified lines
150 """151 _dump_arg_defaults(kwargs, app=app)152 encoding = kwargs.pop("encoding", None)153 rv = _json.dumps(obj, **kwargs)154155 if encoding is not None and isinstance(rv, str):156 rv = rv.encode(encoding)157158 return rv159160161def 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)165166 if encoding is not None:167 fp = _wrap_writer_for_text(fp, encoding)168169 _json.dump(obj, fp, **kwargs)170171172def loads(s, app=None, **kwargs):
2 unmodified lines
175 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the176 default :class:`JSONDecoder`.177178 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.180181 :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 default
5 unmodified lines
189 ``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)194195 if encoding is not None and isinstance(s, bytes):196 s = s.decode(encoding)197198 return _json.loads(s, **kwargs)199200201def 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)207208209_htmlsafe_map = str.maketrans(210 {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026", "'": "\\u0027"}211)212213214def 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 will
17 unmodified lines
235 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)240241242def htmlsafe_dump(obj, fp, **kwargs):243 """Like :func:`htmlsafe_dumps` but writes into a file object."""
75 unmodified lines
modified:tests/test_helpers.py-21 removed
11 unmodified lines
12from werkzeug.http import parse_cache_control_header13from werkzeug.http import parse_options_header1415import flask16from flask import json16from flask.helpers import get_debug_flag17from flask.helpers import get_env1819
42 unmodified lines
62 return datetime.timedelta()636465class 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) == value8666 @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"] = False
932 unmodified lines
modified:CHANGES.rst+3 added
17 unmodified lines
18 :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`252627Version 1.1.228-------------
1011 unmodified lines
modified:tox.ini+1 added-3 removed
1[tox]2envlist =3 py{38,37,36,py3}4 py38-{simplejson,devel,lowest}4 py38-{devel,lowest}5 style6 docs7skip_missing_interpreters = true8
14 unmodified lines
23 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.gz2627 simplejson: simplejson2827commands =28 pip install -q -e examples/tutorial[test]29 pip install -q -e examples/javascript[test]30
10 unmodified lines