Skip to content
Myr

Documented switch to MarkupSafe

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 53675ce · Browse files · 7 files+143 added−290 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+143 added−290 removed

  • other:+143 added−290 removed

7 files+143 added−290 removed

modified:docs/faq.rst+21 added-11 removed
123 unmodified lines
124instead that one can assign to a variable by using set::125126 {% set comments = get_latest_comments() %}127128I don't have the _speedups Module. Is Jinja slower now?129--------------------------------------------------------128What is the speedups module and why is it missing?129--------------------------------------------------130131To achieve a good performance with automatic escaping enabled, the escaping132function is also implemented in pure C and used if Jinja2 was installed with133the speedups module. This happens automatically if a C compiler is available134on the system during installation.132function was also implemented in pure C in older Jinja2 releases and used if133Jinja2 was installed with the speedups module.134135Because this feature itself is very useful for non-template engines as136well it was moved into a separate project on PyPI called `MarkupSafe`_.137138Jinja2 no longer ships with a C implementation of it but only the pure139Python implementation. It will however check if MarkupSafe is available140and installed, and if it is, use the Markup class from MarkupSafe.141142So if you want the speedups, just import MarkupSafe.143144.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe145146My tracebacks look weird. What's happening?147--------------------------------------------148139If the speedups module is not compiled and you are using a Python installation140without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine)141Jinja2 is unable to provide correct debugging information and the traceback142may be incomplete. There is currently no good workaround for Jython or143the AppEngine as ctypes is unavailable there and it's not possible to use144the speedups extension.149If the debugsupport module is not compiled and you are using a Python150installation without ctypes (Python 2.4 without ctypes, Jython or Google's151AppEngine) Jinja2 is unable to provide correct debugging information and152the traceback may be incomplete. There is currently no good workaround153for Jython or the AppEngine as ctypes is unavailable there and it's not154possible to use the debugsupport extension.155156Why is there no Python 2.3 support?157-----------------------------------158
33 unmodified lines
modified:docs/intro.rst+25 added-18 removed
31 unmodified lines
32Prerequisites33-------------3435Jinja2 needs at least **Python 2.4** to run. Additionally a working C-compiler36that can create python extensions should be installed for the debugger. If no37C-compiler is available and you are using Python 2.4 the `ctypes`_ module38should be installed.36that can create python extensions should be installed for the debugger if you37are using Python 2.4.3839If you don't have a working C-compiler and you are trying to install the source41release with the speedups you will get a compiler error. This however can be42circumvented by passing the ``--without-speedups`` command line argument to the43setup script::40release with the debugsupport you will get a compiler error.4145 $ python setup.py --with-speedups install4647(As of Jinja 2.2, the speedups are disabled by default and can be enabled48with ``--with-speedups``. See :ref:`enable-speedups`)4942.. _ctypes: http://python.net/crew/theller/ctypes/434445Installation
56 unmodified lines
102.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall103.. _pip: http://pypi.python.org/pypi/pip104.. _mercurial: http://www.selenic.com/mercurial/105114.. _enable-speedups:106116Enable the speedups Module107More Speed with MarkupSafe108~~~~~~~~~~~~~~~~~~~~~~~~~~109110As of version 2.5.1 Jinja2 will check for an installed `MarkupSafe`_111module. If it can find it, it will use the Markup class of that module112instead of the one that comes with Jinja2. `MarkupSafe` replaces the113older speedups module that came with Jinja2 and has the advantage that is114has a better setup script and will automatically attempt to install the C115version and nicely fall back to a pure Python implementation if that is116not possible.117118The C implementation of MarkupSafe is much faster and recommended when119using Jinja2 with autoescaping.120121.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe122123124Enable the debug support Module125~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~126119By default Jinja2 will not compile the speedups module. Enabling this127By default Jinja2 will not compile the debug support module. Enabling this128will fail if you don't have the Python headers or a working compiler. This129is often the case if you are installing Jinja2 from a windows machine.130123You can enable the speedups extension when installing using the124``--with-speedups`` flag::131Because the debug support is only necessary for Python 2.4 you will not132have to do this unless you run 2.4::133126 sudo python setup.py --with-speedups install134 sudo python setup.py --with-debugsupport install135136129137Basic API Usage138---------------139140This section gives you a brief introduction to the Python API for Jinja2
37 unmodified lines
added:jinja2/_debugsupport.c+78 added
1/**2 * jinja2._debugsupport3 * ~~~~~~~~~~~~~~~~~~~~4 *5 * C implementation of `tb_set_next`.6 *7 * :copyright: (c) 2010 by the Jinja Team.8 * :license: BSD.9 */1011#include <Python.h>121314static PyObject*15tb_set_next(PyObject *self, PyObject *args)16{17 PyTracebackObject *tb, *old;18 PyObject *next;1920 if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))21 return NULL;22 if (next == Py_None)23 next = NULL;24 else if (!PyTraceBack_Check(next)) {25 PyErr_SetString(PyExc_TypeError,26 "tb_set_next arg 2 must be traceback or None");27 return NULL;28 }29 else30 Py_INCREF(next);3132 old = tb->tb_next;33 tb->tb_next = (PyTracebackObject*)next;34 Py_XDECREF(old);3536 Py_INCREF(Py_None);37 return Py_None;38}3940static PyMethodDef module_methods[] = {41 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,42 "Set the tb_next member of a traceback object."},43 {NULL, NULL, 0, NULL} /* Sentinel */44};454647#if PY_MAJOR_VERSION < 34849#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */50#define PyMODINIT_FUNC void51#endif52PyMODINIT_FUNC53init_debugsupport(void)54{55 Py_InitModule3("jinja2._debugsupport", module_methods, "");56}5758#else /* Python 3.x module initialization */5960static struct PyModuleDef module_definition = {61 PyModuleDef_HEAD_INIT,62 "jinja2._debugsupport",63 NULL,64 -1,65 module_methods,66 NULL,67 NULL,68 NULL,69 NULL70};7172PyMODINIT_FUNC73PyInit__debugsupport(void)74{75 return PyModule_Create(&module_definition);76}7778#endif
deleted:jinja2/_speedups.c-258 removed
1/**2 * jinja2._speedups3 * ~~~~~~~~~~~~~~~~4 *5 * This module implements functions for automatic escaping in C for better6 * performance. Additionally it defines a `tb_set_next` function to patch the7 * debug traceback. If the speedups module is not compiled a ctypes8 * implementation of `tb_set_next` and Python implementations of the other9 * functions are used.10 *11 * :copyright: (c) 2009 by the Jinja Team.12 * :license: BSD.13 */1415#include <Python.h>1617#define ESCAPED_CHARS_TABLE_SIZE 6318#define UNICHR(x) (((PyUnicodeObject*)PyUnicode_DecodeASCII(x, strlen(x), NULL))->str);1920#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)21typedef int Py_ssize_t;22#define PY_SSIZE_T_MAX INT_MAX23#define PY_SSIZE_T_MIN INT_MIN24#endif252627static PyObject* markup;28static Py_ssize_t escaped_chars_delta_len[ESCAPED_CHARS_TABLE_SIZE];29static Py_UNICODE *escaped_chars_repl[ESCAPED_CHARS_TABLE_SIZE];3031static int32init_constants(void)33{34 PyObject *module;35 /* happing of characters to replace */36 escaped_chars_repl['"'] = UNICHR("&#34;");37 escaped_chars_repl['\''] = UNICHR("&#39;");38 escaped_chars_repl['&'] = UNICHR("&amp;");39 escaped_chars_repl['<'] = UNICHR("&lt;");40 escaped_chars_repl['>'] = UNICHR("&gt;");4142 /* lengths of those characters when replaced - 1 */43 memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len));44 escaped_chars_delta_len['"'] = escaped_chars_delta_len['\''] = \45 escaped_chars_delta_len['&'] = 4;46 escaped_chars_delta_len['<'] = escaped_chars_delta_len['>'] = 3;47 48 /* import markup type so that we can mark the return value */49 module = PyImport_ImportModule("jinja2.utils");50 if (!module)51 return 0;52 markup = PyObject_GetAttrString(module, "Markup");53 Py_DECREF(module);5455 return 1;56}5758static PyObject*59escape_unicode(PyUnicodeObject *in)60{61 PyUnicodeObject *out;62 Py_UNICODE *inp = in->str;63 const Py_UNICODE *inp_end = in->str + in->length;64 Py_UNICODE *next_escp;65 Py_UNICODE *outp;66 Py_ssize_t delta=0, erepl=0, delta_len=0;6768 /* First we need to figure out how long the escaped string will be */69 while (*(inp) || inp < inp_end) {70 if (*inp < ESCAPED_CHARS_TABLE_SIZE && escaped_chars_delta_len[*inp]) {71 delta += escaped_chars_delta_len[*inp];72 ++erepl;73 }74 ++inp;75 }7677 /* Do we need to escape anything at all? */78 if (!erepl) {79 Py_INCREF(in);80 return (PyObject*)in;81 }8283 out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, in->length + delta);84 if (!out)85 return NULL;8687 outp = out->str;88 inp = in->str;89 while (erepl-- > 0) {90 /* look for the next substitution */91 next_escp = inp;92 while (next_escp < inp_end) {93 if (*next_escp < ESCAPED_CHARS_TABLE_SIZE &&94 (delta_len = escaped_chars_delta_len[*next_escp])) {95 ++delta_len;96 break;97 }98 ++next_escp;99 }100 101 if (next_escp > inp) {102 /* copy unescaped chars between inp and next_escp */103 Py_UNICODE_COPY(outp, inp, next_escp-inp);104 outp += next_escp - inp;105 }106107 /* escape 'next_escp' */108 Py_UNICODE_COPY(outp, escaped_chars_repl[*next_escp], delta_len);109 outp += delta_len;110111 inp = next_escp + 1;112 }113 if (inp < inp_end)114 Py_UNICODE_COPY(outp, inp, in->length - (inp - in->str));115116 return (PyObject*)out;117}118119120static PyObject*121escape(PyObject *self, PyObject *text)122{123 PyObject *s = NULL, *rv = NULL, *html;124125 /* we don't have to escape integers, bools or floats */126 if (PyLong_CheckExact(text) ||127#if PY_MAJOR_VERSION < 3128 PyInt_CheckExact(text) ||129#endif130 PyFloat_CheckExact(text) || PyBool_Check(text) ||131 text == Py_None)132 return PyObject_CallFunctionObjArgs(markup, text, NULL);133134 /* if the object has an __html__ method that performs the escaping */135 html = PyObject_GetAttrString(text, "__html__");136 if (html) {137 rv = PyObject_CallObject(html, NULL);138 Py_DECREF(html);139 return rv;140 }141142 /* otherwise make the object unicode if it isn't, then escape */143 PyErr_Clear();144 if (!PyUnicode_Check(text)) {145#if PY_MAJOR_VERSION < 3146 PyObject *unicode = PyObject_Unicode(text);147#else148 PyObject *unicode = PyObject_Str(text);149#endif150 if (!unicode)151 return NULL;152 s = escape_unicode((PyUnicodeObject*)unicode);153 Py_DECREF(unicode);154 }155 else156 s = escape_unicode((PyUnicodeObject*)text);157158 /* convert the unicode string into a markup object. */159 rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);160 Py_DECREF(s);161 return rv;162}163164165static PyObject*166soft_unicode(PyObject *self, PyObject *s)167{168 if (!PyUnicode_Check(s))169#if PY_MAJOR_VERSION < 3170 return PyObject_Unicode(s);171#else172 return PyObject_Str(s);173#endif174 Py_INCREF(s);175 return s;176}177178179static PyObject*180tb_set_next(PyObject *self, PyObject *args)181{182 PyTracebackObject *tb, *old;183 PyObject *next;184185 if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))186 return NULL;187 if (next == Py_None)188 next = NULL;189 else if (!PyTraceBack_Check(next)) {190 PyErr_SetString(PyExc_TypeError,191 "tb_set_next arg 2 must be traceback or None");192 return NULL;193 }194 else195 Py_INCREF(next);196197 old = tb->tb_next;198 tb->tb_next = (PyTracebackObject*)next;199 Py_XDECREF(old);200201 Py_INCREF(Py_None);202 return Py_None;203}204205static PyMethodDef module_methods[] = {206 {"escape", (PyCFunction)escape, METH_O,207 "escape(s) -> markup\n\n"208 "Convert the characters &, <, >, ', and \" in string s to HTML-safe\n"209 "sequences. Use this if you need to display text that might contain\n"210 "such characters in HTML. Marks return value as markup string."},211 {"soft_unicode", (PyCFunction)soft_unicode, METH_O,212 "soft_unicode(object) -> string\n\n"213 "Make a string unicode if it isn't already. That way a markup\n"214 "string is not converted back to unicode."},215 {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,216 "Set the tb_next member of a traceback object."},217 {NULL, NULL, 0, NULL} /* Sentinel */218};219220221#if PY_MAJOR_VERSION < 3222223#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */224#define PyMODINIT_FUNC void225#endif226PyMODINIT_FUNC227init_speedups(void)228{229 if (!init_constants())230 return;231232 Py_InitModule3("jinja2._speedups", module_methods, "");233}234235#else /* Python 3.x module initialization */236237static struct PyModuleDef module_definition = {238 PyModuleDef_HEAD_INIT,239 "jinja2._speedups",240 NULL,241 -1,242 module_methods,243 NULL,244 NULL,245 NULL,246 NULL247};248249PyMODINIT_FUNC250PyInit__speedups(void)251{252 if (!init_constants())253 return NULL;254255 return PyModule_Create(&module_definition);256}257258#endif
modified:jinja2/debug.py+2 added-2 removed
58 unmodified lines
59 self.exc_value = exc_value60 self.frames = frames6162 def chain_frames(self):63 """Chains the frames. Requires ctypes or the speedups extension."""63 """Chains the frames. Requires ctypes or the debugsupport extension."""64 prev_tb = None65 for tb in self.frames:66 if prev_tb is not None:67 prev_tb.tb_next = tb
230 unmodified lines
298299300# try to get a tb_set_next implementation301try:302 from jinja2._speedups import tb_set_next302 from jinja2._debugsupport import tb_set_next303except ImportError:304 try:305 tb_set_next = _init_ugly_crap()306 except:
2 unmodified lines
modified:CHANGES+5 added
11 unmodified lines
12- improved performance of macro calls slightly.13- babel extraction can now properly extract newstyle gettext calls.14- using the variable `num` in newstyle gettext for something else15 than the pluralize count will no longer raise a :exc:`KeyError`.16- removed builtin markup class and switched to markupsafe. For backwards17 compatibility the pure Python implementation still exists but is18 pulled from markupsafe by the Jinja2 developers. The debug support19 went into a separate feature called "debugsupport" and is disabled20 by default because it is only relevant for Python 2.42122Version 2.523-----------24(codename Incoherence, relased on May 29th 2010)
178 unmodified lines
modified:setup.py+12 added-1 removed
40 unmodified lines
41"""42import os43import sys4445from setuptools import setup45from setuptools import setup, Extension, Feature46from distutils.command.build_ext import build_ext4748debugsupport = Feature(49 'optional C debug support',50 standard=False,51 ext_modules = [52 Extension('jinja2._debugsupport', ['jinja2/_debugsupport.c']),53 ],54)555657# tell distribute to use 2to3 with our own fixers.58extra = {}59if sys.version_info >= (3, 0):60 extra.update(
34 unmodified lines
95 entry_points="""96 [babel.extractors]97 jinja2 = jinja2.ext:babel_extract[i18n]98 """,99 features={'debugsupport': debugsupport},100 **extra101)