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
Provenance
- Commit
10c34da- Tree
35a5896- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
53675ce
7 files changed+143 added−290 removed
modified:docs/faq.rst+21 added-11 removed
123 unmodified lines124 instead that one can assign to a variable by using set::125 126 {% set comments = get_latest_comments() %}127 128-I don't have the _speedups Module. Is Jinja slower now?129---------------------------------------------------------128+What is the speedups module and why is it missing?129+--------------------------------------------------130 131 To achieve a good performance with automatic escaping enabled, the escaping132-function is also implemented in pure C and used if Jinja2 was installed with133-the speedups module. This happens automatically if a C compiler is available134-on the system during installation.132+function was also implemented in pure C in older Jinja2 releases and used if133+Jinja2 was installed with the speedups module.134 135+Because this feature itself is very useful for non-template engines as136+well it was moved into a separate project on PyPI called `MarkupSafe`_.137+138+Jinja2 no longer ships with a C implementation of it but only the pure139+Python implementation. It will however check if MarkupSafe is available140+and installed, and if it is, use the Markup class from MarkupSafe.141+142+So if you want the speedups, just import MarkupSafe.143+144+.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe145+146 My tracebacks look weird. What's happening?147 --------------------------------------------148 139-If the speedups module is not compiled and you are using a Python installation140-without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine)141-Jinja2 is unable to provide correct debugging information and the traceback142-may be incomplete. There is currently no good workaround for Jython or143-the AppEngine as ctypes is unavailable there and it's not possible to use144-the speedups extension.149+If the debugsupport module is not compiled and you are using a Python150+installation without ctypes (Python 2.4 without ctypes, Jython or Google's151+AppEngine) Jinja2 is unable to provide correct debugging information and152+the traceback may be incomplete. There is currently no good workaround153+for Jython or the AppEngine as ctypes is unavailable there and it's not154+possible to use the debugsupport extension.155 156 Why is there no Python 2.3 support?157 -----------------------------------158 33 unmodified linesmodified:docs/intro.rst+25 added-18 removed
31 unmodified lines32 Prerequisites33 -------------34 35 Jinja2 needs at least **Python 2.4** to run. Additionally a working C-compiler36-that can create python extensions should be installed for the debugger. If no37-C-compiler is available and you are using Python 2.4 the `ctypes`_ module38-should be installed.36+that can create python extensions should be installed for the debugger if you37+are using Python 2.4.38 39 If you don't have a working C-compiler and you are trying to install the source41-release with the speedups you will get a compiler error. This however can be42-circumvented by passing the ``--without-speedups`` command line argument to the43-setup script::40+release with the debugsupport you will get a compiler error.41 45- $ python setup.py --with-speedups install46-47-(As of Jinja 2.2, the speedups are disabled by default and can be enabled48-with ``--with-speedups``. See :ref:`enable-speedups`)49-42 .. _ctypes: http://python.net/crew/theller/ctypes/43 44 45 Installation56 unmodified lines102 .. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall103 .. _pip: http://pypi.python.org/pypi/pip104 .. _mercurial: http://www.selenic.com/mercurial/105 114-.. _enable-speedups:106 116-Enable the speedups Module107+More Speed with MarkupSafe108 ~~~~~~~~~~~~~~~~~~~~~~~~~~109 110+As of version 2.5.1 Jinja2 will check for an installed `MarkupSafe`_111+module. If it can find it, it will use the Markup class of that module112+instead of the one that comes with Jinja2. `MarkupSafe` replaces the113+older speedups module that came with Jinja2 and has the advantage that is114+has a better setup script and will automatically attempt to install the C115+version and nicely fall back to a pure Python implementation if that is116+not possible.117+118+The C implementation of MarkupSafe is much faster and recommended when119+using Jinja2 with autoescaping.120+121+.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe122+123+124+Enable the debug support Module125+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~126+119-By default Jinja2 will not compile the speedups module. Enabling this127+By default Jinja2 will not compile the debug support module. Enabling this128 will fail if you don't have the Python headers or a working compiler. This129 is often the case if you are installing Jinja2 from a windows machine.130 123-You can enable the speedups extension when installing using the124-``--with-speedups`` flag::131+Because the debug support is only necessary for Python 2.4 you will not132+have to do this unless you run 2.4::133 126- sudo python setup.py --with-speedups install134+ sudo python setup.py --with-debugsupport install135 136 129-137 Basic API Usage138 ---------------139 140 This section gives you a brief introduction to the Python API for Jinja237 unmodified linesadded: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+ */10+11+#include <Python.h>12+13+14+static PyObject*15+tb_set_next(PyObject *self, PyObject *args)16+{17+ PyTracebackObject *tb, *old;18+ PyObject *next;19+20+ 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);31+32+ old = tb->tb_next;33+ tb->tb_next = (PyTracebackObject*)next;34+ Py_XDECREF(old);35+36+ Py_INCREF(Py_None);37+ return Py_None;38+}39+40+static 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+};45+46+47+#if PY_MAJOR_VERSION < 348+49+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */50+#define PyMODINIT_FUNC void51+#endif52+PyMODINIT_FUNC53+init_debugsupport(void)54+{55+ Py_InitModule3("jinja2._debugsupport", module_methods, "");56+}57+58+#else /* Python 3.x module initialization */59+60+static 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+};71+72+PyMODINIT_FUNC73+PyInit__debugsupport(void)74+{75+ return PyModule_Create(&module_definition);76+}77+78+#endifdeleted: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- */14-15-#include <Python.h>16-17-#define ESCAPED_CHARS_TABLE_SIZE 6318-#define UNICHR(x) (((PyUnicodeObject*)PyUnicode_DecodeASCII(x, strlen(x), NULL))->str);19-20-#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)21-typedef int Py_ssize_t;22-#define PY_SSIZE_T_MAX INT_MAX23-#define PY_SSIZE_T_MIN INT_MIN24-#endif25-26-27-static PyObject* markup;28-static Py_ssize_t escaped_chars_delta_len[ESCAPED_CHARS_TABLE_SIZE];29-static Py_UNICODE *escaped_chars_repl[ESCAPED_CHARS_TABLE_SIZE];30-31-static int32-init_constants(void)33-{34- PyObject *module;35- /* happing of characters to replace */36- escaped_chars_repl['"'] = UNICHR(""");37- escaped_chars_repl['\''] = UNICHR("'");38- escaped_chars_repl['&'] = UNICHR("&");39- escaped_chars_repl['<'] = UNICHR("<");40- escaped_chars_repl['>'] = UNICHR(">");41-42- /* 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);54-55- return 1;56-}57-58-static PyObject*59-escape_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;67-68- /* 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- }76-77- /* Do we need to escape anything at all? */78- if (!erepl) {79- Py_INCREF(in);80- return (PyObject*)in;81- }82-83- out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, in->length + delta);84- if (!out)85- return NULL;86-87- 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- }106-107- /* escape 'next_escp' */108- Py_UNICODE_COPY(outp, escaped_chars_repl[*next_escp], delta_len);109- outp += delta_len;110-111- inp = next_escp + 1;112- }113- if (inp < inp_end)114- Py_UNICODE_COPY(outp, inp, in->length - (inp - in->str));115-116- return (PyObject*)out;117-}118-119-120-static PyObject*121-escape(PyObject *self, PyObject *text)122-{123- PyObject *s = NULL, *rv = NULL, *html;124-125- /* 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);133-134- /* 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- }141-142- /* 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);157-158- /* convert the unicode string into a markup object. */159- rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);160- Py_DECREF(s);161- return rv;162-}163-164-165-static PyObject*166-soft_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-}177-178-179-static PyObject*180-tb_set_next(PyObject *self, PyObject *args)181-{182- PyTracebackObject *tb, *old;183- PyObject *next;184-185- 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);196-197- old = tb->tb_next;198- tb->tb_next = (PyTracebackObject*)next;199- Py_XDECREF(old);200-201- Py_INCREF(Py_None);202- return Py_None;203-}204-205-static 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-};219-220-221-#if PY_MAJOR_VERSION < 3222-223-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */224-#define PyMODINIT_FUNC void225-#endif226-PyMODINIT_FUNC227-init_speedups(void)228-{229- if (!init_constants())230- return;231-232- Py_InitModule3("jinja2._speedups", module_methods, "");233-}234-235-#else /* Python 3.x module initialization */236-237-static 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-};248-249-PyMODINIT_FUNC250-PyInit__speedups(void)251-{252- if (!init_constants())253- return NULL;254-255- return PyModule_Create(&module_definition);256-}257-258-#endifmodified:jinja2/debug.py+2 added-2 removed
58 unmodified lines59 self.exc_value = exc_value60 self.frames = frames61 62 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 = tb230 unmodified lines298 299 300 # try to get a tb_set_next implementation301 try:302- from jinja2._speedups import tb_set_next302+ from jinja2._debugsupport import tb_set_next303 except ImportError:304 try:305 tb_set_next = _init_ugly_crap()306 except:2 unmodified linesmodified:CHANGES+5 added
11 unmodified lines12 - 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.421 22 Version 2.523 -----------24 (codename Incoherence, relased on May 29th 2010)178 unmodified linesmodified:setup.py+12 added-1 removed
40 unmodified lines41 """42 import os43 import sys44 45-from setuptools import setup45+from setuptools import setup, Extension, Feature46+from distutils.command.build_ext import build_ext47 48+debugsupport = Feature(49+ 'optional C debug support',50+ standard=False,51+ ext_modules = [52+ Extension('jinja2._debugsupport', ['jinja2/_debugsupport.c']),53+ ],54+)55+56+57 # tell distribute to use 2to3 with our own fixers.58 extra = {}59 if sys.version_info >= (3, 0):60 extra.update(34 unmodified lines95 entry_points="""96 [babel.extractors]97 jinja2 = jinja2.ext:babel_extract[i18n]98 """,99+ features={'debugsupport': debugsupport},100 **extra101 )