deprecate JSON encoding options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
make consistent with built-in json module
authored by David Lord · committed by David Lord · parent c43edfc · Browse files · 2 files·+54 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+54 added−49 removed
- tests:+0 added−1 removed
- other:+54 added−48 removed
Provenance
- Commit
8b5f760- Tree
a2e2fb4- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
c43edfc
2 files changed+54 added−49 removed
modified:src/flask/json/__init__.py+54 added-48 removed
1 import io2 import json as _json3 import uuid4+import warnings5 from datetime import date6 from datetime import datetime7 7-from jinja2 import Markup8+from markupsafe import Markup9 from werkzeug.http import http_date10 11 from ..globals import current_app12 from ..globals import request4 unmodified lines17 # Python < 3.718 dataclasses = None19 20 20-__all__ = [21- "dump",22- "dumps",23- "load",24- "loads",25- "htmlsafe_dump",26- "htmlsafe_dumps",27- "JSONDecoder",28- "JSONEncoder",29- "jsonify",30-]31-32-33-def _wrap_reader_for_text(fp, encoding):34- if isinstance(fp.read(0), bytes):35- fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)36- return fp37-38-39-def _wrap_writer_for_text(fp, encoding):40- try:41- fp.write("")42- except TypeError:43- fp = io.TextIOWrapper(fp, encoding)44- return fp45-46-21 class 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.31 unmodified lines56 if dataclasses and dataclasses.is_dataclass(o):57 return dataclasses.asdict(o)58 if hasattr(o, "__html__"):59 return str(o.__html__())86- return _json.JSONEncoder.default(self, o)60+ return super().default(self, o)61 62 63 class JSONDecoder(_json.JSONDecoder):64 """The default JSON decoder. This one does not change the behavior from9 unmodified lines74 app = current_app75 76 if app:77 bp = app.blueprints.get(request.blueprint) if request else None104- kwargs.setdefault(105- "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder106- )107-108- if not app.config["JSON_AS_ASCII"]:109- kwargs.setdefault("ensure_ascii", False)110-78+ cls = bp.json_encoder if bp and bp.json_encoder else app.json_encoder79+ kwargs.setdefault("cls", cls)80+ kwargs.setdefault("ensure_ascii", app.config["JSON_AS_ASCII"])81 kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])82 else:83 kwargs.setdefault("sort_keys", True)84 kwargs.setdefault("cls", JSONEncoder)5 unmodified lines90 app = current_app91 92 if app:93 bp = app.blueprints.get(request.blueprint) if request else None124- kwargs.setdefault(125- "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder126- )94+ cls = bp.json_decoder if bp and bp.json_decoder else app.json_decoder95+ kwargs.setdefault("cls", cls)96 else:97 kwargs.setdefault("cls", JSONDecoder)98 99 20 unmodified lines120 _dump_arg_defaults(kwargs, app=app)121 encoding = kwargs.pop("encoding", None)122 rv = _json.dumps(obj, **kwargs)123 155- if encoding is not None and isinstance(rv, str):156- rv = rv.encode(encoding)124+ if encoding is not None:125+ warnings.warn(126+ "'encoding' is deprecated and will be removed in 2.1.",127+ DeprecationWarning,128+ stacklevel=2,129+ )130 131+ if isinstance(rv, str):132+ return rv.encode(encoding)133+134 return rv135 136 137 def dump(obj, fp, app=None, **kwargs):138 """Like :func:`dumps` but writes into a file object."""139 _dump_arg_defaults(kwargs, app=app)140 encoding = kwargs.pop("encoding", None)141+ show_warning = encoding is not None142 166- if encoding is not None:167- fp = _wrap_writer_for_text(fp, encoding)143+ try:144+ fp.write("")145+ except TypeError:146+ show_warning = True147+ fp = io.TextIOWrapper(fp, encoding or "utf-8")148 149+ if show_warning:150+ warnings.warn(151+ "Writing to a binary file, and the 'encoding' argument, is"152+ " deprecated and will be removed in 2.1.",153+ DeprecationWarning,154+ stacklevel=2,155+ )156+157 _json.dump(obj, fp, **kwargs)158 159 160 def loads(s, app=None, **kwargs):18 unmodified lines179 """180 _load_arg_defaults(kwargs, app=app)181 encoding = kwargs.pop("encoding", None)182 195- if encoding is not None and isinstance(s, bytes):196- s = s.decode(encoding)183+ if encoding is not None:184+ warnings.warn(185+ "'encoding' is deprecated and will be removed in 2.1. The"186+ " data must be a string or UTF-8 bytes.",187+ DeprecationWarning,188+ stacklevel=2,189+ )190 191+ if isinstance(s, bytes):192+ s = s.decode(encoding)193+194 return _json.loads(s, **kwargs)195 196 197 def load(fp, app=None, **kwargs):198 """Like :func:`loads` but reads from a file object."""199 _load_arg_defaults(kwargs, app=app)200 encoding = kwargs.pop("encoding", None)205- fp = _wrap_reader_for_text(fp, encoding or "utf-8")201+202+ if encoding is not None:203+ warnings.warn(204+ "'encoding' is deprecated and will be removed in 2.1. The"205+ " file must be text mode, or binary mode with UTF-8 bytes.",206+ DeprecationWarning,207+ stacklevel=2,208+ )209+210+ if isinstance(fp.read(0), bytes):211+ fp = io.TextIOWrapper(fp, encoding)212+213 return _json.load(fp, **kwargs)214 215 216 _htmlsafe_map = str.maketrans(30 unmodified lines247 248 249 def htmlsafe_dump(obj, fp, **kwargs):250 """Like :func:`htmlsafe_dumps` but writes into a file object."""244- fp.write(str(htmlsafe_dumps(obj, **kwargs)))251+ fp.write(htmlsafe_dumps(obj, **kwargs))252 253 254 def jsonify(*args, **kwargs):255 """This function wraps :func:`dumps` to add a few enhancements that make43 unmodified lines299 currently means no indents and no spaces after separators.300 301 .. versionadded:: 0.2302 """296-303 indent = None304 separators = (",", ":")305 306 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:18 unmodified linesmodified:tests/test_helpers.py-1 removed
230 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"'235- 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 lines