Skip to content
Myr

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

7 files+46 added−31 removed

modified:docs/patterns/jquery.rst+8 added-3 removed
61 unmodified lines
62 <script type=text/javascript>63 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};64 </script>6566The ``|safe`` is necessary so that Jinja does not escape the JSON encoded67string with HTML rules. Usually this would be necessary, but we are68inside a `script` block here where different rules apply.66The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67escape the JSON encoded string with HTML rules. Usually this would be68necessary, but we are inside a `script` block here where different rules69apply.7071.. admonition:: Information for Pros7273 In HTML the `script` tag is declared `CDATA` which means that entities
2 unmodified lines
76 tags. ``|tojson`` is kind enough to do the right thing here and77 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as78 ``"<\/script>"``).7980 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.838485JSON View Functions86-------------------8788Now let's create a server side function that accepts two URL arguments of
80 unmodified lines
modified:docs/api.rst+2 added-3 removed
362 unmodified lines
363364The :func:`~htmlsafe_dumps` function of this json module is also available365as filter called ``|tojson`` in Jinja2. Note that inside `script`366tags no escaping must take place, so make sure to disable escaping367with ``|safe`` if you intend to use it inside `script` tags:367with ``|safe`` if you intend to use it inside `script` tags unless368you are using Flask 0.10 which implies that:369370.. sourcecode:: html+jinja371372 <script type=text/javascript>373 doSomethingWith({{ user.username|tojson|safe }});374 </script>375375Note that the ``|tojson`` filter escapes forward slashes properly.376376.. autofunction:: jsonify377378.. autofunction:: dumps379
340 unmodified lines
modified:docs/templating.rst+2 added-4 removed
104 unmodified lines
105 is for example very helpful if you try to generate JavaScript on the106 fly.107108 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:111112 .. sourcecode:: html+jinja113114 <script type=text/javascript>115 doSomethingWith({{ user.username|tojson|safe }});116 </script>117118 That the ``|tojson`` filter escapes forward slashes properly for you.119118Controlling Autoescaping119------------------------120121Autoescaping is the concept of automatically escaping special characters
101 unmodified lines
modified:flask/testsuite/helpers.py+11 added-6 removed
90 unmodified lines
91 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"')106107 def test_json_customization(self):108 class X(object):109 def __init__(self, val):
477 unmodified lines
modified:flask/app.py+1 added-8 removed
657 unmodified lines
658 request=request,659 session=session,660 g=g661 )662 rv.filters['tojson'] = json.htmlsafe_dumps662 rv.filters['tojson'] = json.tojson_filter663 return rv664665 def create_global_jinja_loader(self):666 """Creates the loader for the Jinja2 environment. Can be used to
1039 unmodified lines
1706 for func in funcs:1707 rv = func(exc)1708 request_tearing_down.send(self, exc=exc)17091710 # 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()17161710 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 lines
modified:flask/json.py+20 added-7 removed
13 unmodified lines
14from .globals import current_app, request15from ._compat import text_type, PY21617from werkzeug.http import http_date18from jinja2 import Markup1920# Use the same json implementation as itsdangerous on which we21# depend anyways.22try:
137 unmodified lines
160161def 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.167168 .. 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 rv179180181def 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)))184185186def jsonify(*args, **kwargs):187 """Creates a :class:`~flask.Response` with the JSON representation of
33 unmodified lines
221 indent = 2222 return current_app.response_class(dumps(dict(*args, **kwargs),223 indent=indent),224 mimetype='application/json')225226227def tojson_filter(obj, **kwargs):228 return Markup(htmlsafe_dumps(obj, **kwargs))
modified:CHANGES+2 added
15 unmodified lines
16- 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 how
416 unmodified lines