Merge pull request #3195 from eruvanos/json_support_dataclass
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Support dataclass in JSONEncoder (if available)
authored by David Lord · committed by GitHub · parents dbd3840, 6af14f0 · Browse files · 3 files·+26 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+26 added−5 removed
- tests:+9 added−0 removed
- other:+17 added−5 removed
Provenance
- Commit
b0185a6- Tree
39f4638- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
dbd3840- Parent 2
6af14f0
3 files changed+26 added−5 removed
modified:flask/json/__init__.py+15 added-5 removed
18 unmodified lines19 # Use the same json implementation as itsdangerous on which we20 # depend anyways.21 from itsdangerous import json as _json22 23+try:24+ import dataclasses25+except ImportError:26+ dataclasses = None27 28 # Figure out if simplejson escapes slashes. This behavior was changed29 # from one version to another without reason.30 _slash_escape = "\\/" not in _json.dumps("/")26 unmodified lines57 return fp58 59 60 class JSONEncoder(_json.JSONEncoder):57- """The default Flask JSON encoder. This one extends the default simplejson58- encoder by also supporting ``datetime`` objects, ``UUID`` as well as59- ``Markup`` objects which are serialized as RFC 822 datetime strings (same60- as the HTTP date format). In order to support more data types override the61- :meth:`default` method.61+ """The default Flask JSON encoder. This one extends the default62+ encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,63+ and ``Markup`` objects.64+65+ ``datetime`` objects are serialized as RFC 822 datetime strings.66+ This is the same as the HTTP date format.67+68+ In order to support more data types, override the :meth:`default`69+ method.70 """71 72 def default(self, o):73 """Implement this method in a subclass such that it returns a17 unmodified lines91 if isinstance(o, date):92 return http_date(o.timetuple())93 if isinstance(o, uuid.UUID):94 return str(o)95+ if dataclasses and dataclasses.is_dataclass(o):96+ return dataclasses.asdict(o)97 if hasattr(o, "__html__"):98 return text_type(o.__html__())99 return _json.JSONEncoder.default(self, o)100 275 unmodified linesmodified:tests/test_basic.py+9 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import re13+import sys14 import time15 import uuid16 from datetime import datetime17 from threading import Thread1271 unmodified lines1289 rv = flask.make_response(flask.jsonify(msg), 200)1290 assert rv.mimetype == "application/vnd.api+json"1291 1292 1293+@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")1294+def test_json_dump_dataclass(app, req_ctx):1295+ from dataclasses import make_dataclass1296+ Data = make_dataclass("Data", [("name", str)])1297+ value = flask.json.dumps(Data("Flask"), app=app)1298+ value = flask.json.loads(value, app=app)1299+ assert value == {"name": "Flask"}1300+1301 def test_jsonify_args_and_kwargs_check(app, req_ctx):1302 with pytest.raises(TypeError) as e:1303 flask.jsonify("fake args", kwargs="fake")1304 assert "behavior undefined" in str(e.value)660 unmodified linesmodified:CHANGES.rst+2 added
36 unmodified lines37 of Werkzeug 0.15's better reloader support. This bumps the Werkzeug38 dependency to >= 0.15. :issue:`3022`39 - Support ``static_url_path`` that ends with a forward slash.40 :issue:`3134`41+- :meth:`jsonify` supports :class:`dataclasses.dataclass` objects.42+ :pr:`3195`43 44 .. _#2935: https://github.com/pallets/flask/issues/293545 .. _#2957: https://github.com/pallets/flask/issues/295746 .. _#2994: https://github.com/pallets/flask/pull/2994948 unmodified lines