Added README.rst.
Marc Brinkmann
8 years ago
0 | Jinja vanish: Escape like a ninja | |
1 | ================================= | |
2 | ||
3 | When using `Jinja2`_-templates to output non-HTML contents, autoescaping cannot | |
4 | be used because it is hardcoded to work with an HTML ``escape`` function and | |
5 | `MarkupSafe`_'s Markup objects. | |
6 | ||
7 | `jinja_vanish` enables implementing custom auto-escapes by overriding the | |
8 | ``escape`` function inside the generated template code using an extended | |
9 | code-generator and replacing the built-in filters ``|e`` and ``|escape``. Usage | |
10 | is fairly simple, here is an example that uses `psycopg2`'s ``mogrify()`` | |
11 | function to escape SQL for Postgres: | |
12 | ||
13 | .. code-block:: python | |
14 | ||
15 | from datetime import datetime | |
16 | ||
17 | from jinja_vanish import DynEscapeAutoenvironment, markup_escape_func | |
18 | from psycopg2.extensions import adapt | |
19 | ||
20 | @markup_escape_func | |
21 | def sql_escape(v): | |
22 | # the decorator handles wrapping/unwrapping in Markup(), but is | |
23 | # otherwise not necessary | |
24 | return adapt(v) | |
25 | ||
26 | ||
27 | env = DynEscapeAutoenvironment(autoescape=True, escape_func=sql_escape) | |
28 | tpl = env.from_string('SELECT * FROM foo where post_date <= {{now}}') | |
29 | ||
30 | print(tpl.render(now=datetime.now())) | |
31 | ||
32 | Running it outputs:: | |
33 | ||
34 | SELECT * FROM foo where post_date <= '2016-01-24T23:23:22.727789'::timestamp | |
35 | ||
36 | ||
37 | ||
38 | .. _Jinja2: http://jinja.pocoo.org | |
39 | .. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe |