Imply the |safe on tojson in templates and change escaping logic
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 56d3b74 · Browse files · 7 files·+46 added−31 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+46 added−31 removed
- other:+46 added−31 removed
Provenance
- Commit
ef72b78- Tree
e06f06c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
56d3b74
7 files changed+46 added−31 removed
modified:docs/patterns/jquery.rst+8 added-3 removed
61 unmodified lines62 <script type=text/javascript>63 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};64 </script>65 66-The ``|safe`` is necessary so that Jinja does not escape the JSON encoded67-string with HTML rules. Usually this would be necessary, but we are68-inside a `script` block here where different rules apply.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.70 71 .. admonition:: Information for Pros72 73 In HTML the `script` tag is declared `CDATA` which means that entities2 unmodified lines76 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+85 JSON View Functions86 -------------------87 88 Now let's create a server side function that accepts two URL arguments of80 unmodified linesmodified:docs/api.rst+2 added-3 removed
362 unmodified lines363 364 The :func:`~htmlsafe_dumps` function of this json module is also available365 as filter called ``|tojson`` in Jinja2. Note that inside `script`366 tags no escaping must take place, so make sure to disable escaping367-with ``|safe`` if you intend to use it inside `script` tags:367+with ``|safe`` if you intend to use it inside `script` tags unless368+you are using Flask 0.10 which implies that:369 370 .. sourcecode:: html+jinja371 372 <script type=text/javascript>373 doSomethingWith({{ user.username|tojson|safe }});374 </script>375 375-Note that the ``|tojson`` filter escapes forward slashes properly.376-376 .. autofunction:: jsonify377 378 .. autofunction:: dumps379 340 unmodified linesmodified:docs/templating.rst+2 added-4 removed
104 unmodified lines105 is for example very helpful if you try to generate JavaScript on the106 fly.107 108 Note that inside `script` tags no escaping must take place, so make109- sure to disable escaping with ``|safe`` if you intend to use it inside110- `script` tags:109+ sure to disable escaping with ``|safe`` before Flask 0.10 if you intend110+ to use it inside `script` tags:111 112 .. sourcecode:: html+jinja113 114 <script type=text/javascript>115 doSomethingWith({{ user.username|tojson|safe }});116 </script>117 118- That the ``|tojson`` filter escapes forward slashes properly for you.119-118 Controlling Autoescaping119 ------------------------120 121 Autoescaping is the concept of automatically escaping special characters101 unmodified linesmodified:flask/testsuite/helpers.py+11 added-6 removed
90 unmodified lines91 def test_template_escaping(self):92 app = flask.Flask(__name__)93 render = flask.render_template_string94 with app.test_request_context():95+ rv = flask.json.htmlsafe_dumps('</script>')96+ self.assert_equal(rv, u'"\\u003c/script\\u003e"')97+ self.assert_equal(type(rv), text_type)95- rv = render('{{ "</script>"|tojson|safe }}')96- self.assert_equal(rv, '"<\\/script>"')97- rv = render('{{ "<\0/script>"|tojson|safe }}')98- self.assert_equal(rv, '"<\\u0000\\/script>"')99- rv = render('{{ "<!--<script>"|tojson|safe }}')100- self.assert_equal(rv, '"<\\u0021--<script>"')98+ rv = render('{{ "</script>"|tojson }}')99+ self.assert_equal(rv, '"\\u003c/script\\u003e"')100+ rv = render('{{ "<\0/script>"|tojson }}')101+ self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')102+ rv = render('{{ "<!--<script>"|tojson }}')103+ self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')104+ rv = render('{{ "&"|tojson }}')105+ self.assert_equal(rv, '"\\u0026"')106 107 def test_json_customization(self):108 class X(object):109 def __init__(self, val):477 unmodified linesmodified:flask/app.py+1 added-8 removed
657 unmodified lines658 request=request,659 session=session,660 g=g661 )662- rv.filters['tojson'] = json.htmlsafe_dumps662+ rv.filters['tojson'] = json.tojson_filter663 return rv664 665 def create_global_jinja_loader(self):666 """Creates the loader for the Jinja2 environment. Can be used to1039 unmodified lines1706 for func in funcs:1707 rv = func(exc)1708 request_tearing_down.send(self, exc=exc)1709 1710- # If this interpreter supports clearing the exception information1711- # we do that now. This will only go into effect on Python 2.x,1712- # on 3.x it disappears automatically at the end of the exception1713- # stack.1714- if hasattr(sys, 'exc_clear'):1715- sys.exc_clear()1716-1710 def do_teardown_appcontext(self, exc=None):1711 """Called when an application context is popped. This works pretty1712 much the same as :meth:`do_teardown_request` but for the application1713 context.122 unmodified linesmodified:flask/json.py+20 added-7 removed
13 unmodified lines14 from .globals import current_app, request15 from ._compat import text_type, PY216 17 from werkzeug.http import http_date18+from jinja2 import Markup19 20 # Use the same json implementation as itsdangerous on which we21 # depend anyways.22 try:137 unmodified lines160 161 def htmlsafe_dumps(obj, **kwargs):162 """Works exactly like :func:`dumps` but is safe for use in ``<script>``163 tags. It accepts the same arguments and returns a JSON string. Note that163- this is available in templates through the ``|tojson`` filter but it will164- have to be wrapped in ``|safe`` unless **true** XHTML is being used.164+ this is available in templates through the ``|tojson`` filter which will165+ also mark the result as safe. Due to how this function escapes certain166+ characters this is safe even if used outside of ``<script>`` tags.167+168+ .. versionchanged:: 0.10169+ This function's return value is now always safe for HTML usage, even170+ if outside of script tags or if used in XHTML.171 """166- rv = dumps(obj, **kwargs)167- if _slash_escape:168- rv = rv.replace('/', '\\/')169- return rv.replace('<!', '<\\u0021')172+ rv = dumps(obj, **kwargs) \173+ .replace(u'<', u'\\u003c') \174+ .replace(u'>', u'\\u003e') \175+ .replace(u'&', u'\\u0026')176+ if not _slash_escape:177+ rv = rv.replace('\\/', '/')178+ return rv179 180 181 def htmlsafe_dump(obj, fp, **kwargs):182 """Like :func:`htmlsafe_dumps` but writes into a file object."""174- fp.write(htmlsafe_dumps(obj, **kwargs))183+ fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))184 185 186 def jsonify(*args, **kwargs):187 """Creates a :class:`~flask.Response` with the JSON representation of33 unmodified lines221 indent = 2222 return current_app.response_class(dumps(dict(*args, **kwargs),223 indent=indent),224 mimetype='application/json')225+226+227+def tojson_filter(obj, **kwargs):228+ return Markup(htmlsafe_dumps(obj, **kwargs))modified:CHANGES+2 added
15 unmodified lines16 - Added ``template_global`` methods in addition to the already existing17 ``template_filter`` method family.18 - Set the content-length header for x-sendfile.19 - ``tojson`` filter now does not escape script blocks in HTML5 parsers.20+- ``tojson`` used in templates is now safe by default due. This was21+ allowed due to the different escaping behavior.22 - Flask will now raise an error if you attempt to register a new function23 on an already used endpoint.24 - Added wrapper module around simplejson and added default serialization25 of datetime objects. This allows much easier customization of how416 unmodified lines