Merge pull request #3895 from pallets/jinja-tojson
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use Jinja's tojson filter
authored by David Lord · committed by GitHub · parents fdf5d11, b473e7c · Browse files · 7 files·+28 added−88 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+28 added−88 removed
- tests:+10 added−17 removed
- other:+18 added−71 removed
Provenance
- Commit
192f4ae- Tree
ee79d8f- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
fdf5d11- Parent 2
b473e7c
7 files changed+28 added−88 removed
modified:docs/patterns/jquery.rst+1 added-19 removed
58 unmodified lines59 60 .. sourcecode:: html+jinja61 62 <script type=text/javascript>63- $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};63+ $SCRIPT_ROOT = {{ request.script_root|tojson }};64 </script>65 66-The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67-escape the JSON encoded string with HTML rules. Usually this would be68-necessary, but we are inside a ``script`` block here where different rules69-apply.66 71-.. admonition:: Information for Pros72-73- In HTML the ``script`` tag is declared ``CDATA`` which means that entities74- will not be parsed. Everything until ``</script>`` is handled as script.75- This also means that there must never be any ``</`` between the script76- tags. ``|tojson`` is kind enough to do the right thing here and77- escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as78- ``"<\/script>"``).79-80- In Flask 0.10 it goes a step further and escapes all HTML tags with81- unicode escapes. This makes it possible for Flask to automatically82- mark the result as HTML safe.83-84-67 JSON View Functions68 -------------------69 70 Now let's create a server side function that accepts two URL arguments of79 unmodified linesmodified:docs/api.rst+5 added-4 removed
248 unmodified lines249 :func:`dataclasses.asdict`.250 - :class:`~markupsafe.Markup` (or any object with a ``__html__``251 method) will call the ``__html__`` method to get a string.252 253-:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template254-filter. The filter marks the output with ``|safe`` so it can be used255-inside ``script`` tags.253+Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`254+function. The filter marks the output with ``|safe`` automatically. Use255+the filter to render data inside ``<script>`` tags.256 257 .. sourcecode:: html+jinja258 259 <script type=text/javascript>260+ const names = {{ names|tosjon }};260- renderChart({{ axis_data|tojson }});261+ renderChart(names, {{ axis_data|tojson }});262 </script>263 264 .. autofunction:: jsonify265 510 unmodified linesmodified:docs/templating.rst-31 removed
93 unmodified lines94 .. sourcecode:: jinja95 96 {% from '_helpers.html' import my_macro with context %}97 98-Standard Filters99-----------------98 101-Flask provides the following Jinja2 filters in addition to the filters provided102-by Jinja2 itself:103-104-.. function:: tojson105- :noindex:106-107- This function converts the given object into JSON representation. This108- is for example very helpful if you try to generate JavaScript on the109- fly.110-111- .. sourcecode:: html+jinja112-113- <script type=text/javascript>114- doSomethingWith({{ user.username|tojson }});115- </script>116-117- It is also safe to use the output of `|tojson` in a *single-quoted* HTML118- attribute:119-120- .. sourcecode:: html+jinja121-122- <button onclick='doSomethingWith({{ user.username|tojson }})'>123- Click me124- </button>125-126- Note that in versions of Flask prior to 0.10, if using the output of127- ``|tojson`` inside ``script``, make sure to disable escaping with ``|safe``.128- In Flask 0.10 and above, this happens automatically.129-99 Controlling Autoescaping100 ------------------------101 102 Autoescaping is the concept of automatically escaping special characters101 unmodified linesmodified:src/flask/json/__init__.py+10 added-16 removed
3 unmodified lines4 import warnings5 from datetime import date6 from datetime import datetime7 8-from markupsafe import Markup8+from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9 from werkzeug.http import http_date10 11 from ..globals import current_app12 from ..globals import request220 unmodified lines233 234 return _json.load(fp, **kwargs)235 236 237-_htmlsafe_map = str.maketrans(238- {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026", "'": "\\u0027"}239-)240-241-237 def htmlsafe_dumps(obj, **kwargs):243- """Serialize an object to a string of JSON, replacing HTML-unsafe244- characters with Unicode escapes. Otherwise behaves the same as245- :func:`dumps`.238+ """Serialize an object to a string of JSON with :func:`dumps`, then239+ replace HTML-unsafe characters with Unicode escapes and mark the240+ result safe with :class:`~markupsafe.Markup`.241 247- This is available in templates as the ``|tojson`` filter, which will248- also mark the result with ``|safe``.242+ This is available in templates as the ``|tojson`` filter.243 244 The returned string is safe to render in HTML documents and245 ``<script>`` tags. The exception is in HTML attributes that are246 double quoted; either use single quotes or the ``|forceescape``247 filter.248 249+ .. versionchanged:: 2.0250+ Uses :func:`jinja2.utils.htmlsafe_json_dumps`. The returned251+ value is marked safe by wrapping in :class:`~markupsafe.Markup`.252+253 .. versionchanged:: 0.10254 Single quotes are escaped, making this safe to use in HTML,255 ``<script>`` tags, and single-quoted attributes without further256 escaping.257 """260- return dumps(obj, **kwargs).translate(_htmlsafe_map)258+ return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)259 260 261 def htmlsafe_dump(obj, fp, **kwargs):262 """Serialize an object to JSON written to a file object, replacing69 unmodified lines332 return current_app.response_class(333 f"{dumps(data, indent=indent, separators=separators)}\n",334 mimetype=current_app.config["JSONIFY_MIMETYPE"],335 )338-339-340-def tojson_filter(obj, **kwargs):341- return Markup(htmlsafe_dumps(obj, **kwargs))modified:src/flask/app.py+1 added-1 removed
679 unmodified lines680 request=request,681 session=session,682 g=g,683 )684- rv.filters["tojson"] = json.tojson_filter684+ rv.policies["json.dumps_function"] = json.dumps685 return rv686 687 def create_global_jinja_loader(self):688 """Creates the loader for the Jinja2 environment. Can be used to1344 unmodified linesmodified:tests/test_json.py+10 added-17 removed
202 unmodified lines203 )204 assert rv.data == b"3"205 206 207-def test_template_escaping(app, req_ctx):208- render = flask.render_template_string209- rv = flask.json.htmlsafe_dumps("</script>")210- assert rv == '"\\u003c/script\\u003e"'211- rv = render('{{ "</script>"|tojson }}')212- assert rv == '"\\u003c/script\\u003e"'213- rv = render('{{ "<\0/script>"|tojson }}')214- assert rv == '"\\u003c\\u0000/script\\u003e"'215- rv = render('{{ "<!--<script>"|tojson }}')216- assert rv == '"\\u003c!--\\u003cscript\\u003e"'217- rv = render('{{ "&"|tojson }}')218- assert rv == '"\\u0026"'219- rv = render('{{ "\'"|tojson }}')220- assert rv == '"\\u0027"'221- rv = render(222- "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]}207+def test_tojson_filter(app, req_ctx):208+ # The tojson filter is tested in Jinja, this confirms that it's209+ # using Flask's dumps.210+ rv = flask.render_template_string(211+ "const data = {{ data|tojson }};",212+ data={"name": "</script>", "time": datetime.datetime(2021, 2, 1, 7, 15)},213 )224- assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'214+ assert rv == (215+ 'const data = {"name": "\\u003c/script\\u003e",'216+ ' "time": "Mon, 01 Feb 2021 07:15:00 GMT"};'217+ )218 219 220 def test_json_customization(app, client):221 class X: # noqa: B903, for Python2 compatibility184 unmodified linesmodified:CHANGES.rst+1 added
61 unmodified lines62 ``werkzeug.utils.safe_join`` instead. :pr:`3828`63 - The request context does route matching before opening the session.64 This could allow a session interface to change behavior based on65 ``request.endpoint``. :issue:`3776`66+- Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881`67 68 69 Version 1.1.270 -------------1011 unmodified lines