Skip to content
Myr

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

2 files+54 added−49 removed

modified:src/flask/json/__init__.py+54 added-48 removed
1import io2import json as _json3import uuid4import warnings5from datetime import date6from datetime import datetime77from jinja2 import Markup8from markupsafe import Markup9from werkzeug.http import http_date1011from ..globals import current_app12from ..globals import request
4 unmodified lines
17 # Python < 3.718 dataclasses = None192020__all__ = [21 "dump",22 "dumps",23 "load",24 "loads",25 "htmlsafe_dump",26 "htmlsafe_dumps",27 "JSONDecoder",28 "JSONEncoder",29 "jsonify",30]313233def _wrap_reader_for_text(fp, encoding):34 if isinstance(fp.read(0), bytes):35 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)36 return fp373839def _wrap_writer_for_text(fp, encoding):40 try:41 fp.write("")42 except TypeError:43 fp = io.TextIOWrapper(fp, encoding)44 return fp454621class 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 lines
56 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)616263class JSONDecoder(_json.JSONDecoder):64 """The default JSON decoder. This one does not change the behavior from
9 unmodified lines
74 app = current_app7576 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 )107108 if not app.config["JSON_AS_ASCII"]:109 kwargs.setdefault("ensure_ascii", False)11078 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 lines
90 app = current_app9192 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)9899
20 unmodified lines
120 _dump_arg_defaults(kwargs, app=app)121 encoding = kwargs.pop("encoding", None)122 rv = _json.dumps(obj, **kwargs)123155 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 )130131 if isinstance(rv, str):132 return rv.encode(encoding)133134 return rv135136137def 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 None142166 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")148149 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 )156157 _json.dump(obj, fp, **kwargs)158159160def loads(s, app=None, **kwargs):
18 unmodified lines
179 """180 _load_arg_defaults(kwargs, app=app)181 encoding = kwargs.pop("encoding", None)182195 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 )190191 if isinstance(s, bytes):192 s = s.decode(encoding)193194 return _json.loads(s, **kwargs)195196197def 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")201202 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 )209210 if isinstance(fp.read(0), bytes):211 fp = io.TextIOWrapper(fp, encoding)212213 return _json.load(fp, **kwargs)214215216_htmlsafe_map = str.maketrans(
30 unmodified lines
247248249def 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))252253254def jsonify(*args, **kwargs):255 """This function wraps :func:`dumps` to add a few enhancements that make
43 unmodified lines
299 currently means no indents and no spaces after separators.300301 .. versionadded:: 0.2302 """296303 indent = None304 separators = (",", ":")305306 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
18 unmodified lines
modified:tests/test_helpers.py-1 removed
230 unmodified lines
231 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