[svn] added c implementation of cgi.escape to jinja (fast for unicode, awefully slow for str)
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 157d7e5 · Browse files · 5 files·+115 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+115 added−11 removed
- other:+115 added−11 removed
Provenance
- Commit
4a51133- Tree
a1e8777- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
157d7e5
5 files changed+115 added−11 removed
modified:jinja/_native.py+4 added-2 removed
21 unmodified lines22 def __init__(self, silent, globals, initial):23 self._silent = silent24 self.current = current = {}25 self.stack = [globals, initial, current]26+ self._push = self.stack.append27+ self._pop = self.stack.pop28 self.globals = globals29 self.initial = initial30 31 def pop(self):32 """33 Pop the last layer from the stack and return it.34 """33- rv = self.stack.pop()35+ rv = self._pop()36 self.current = self.stack[-1]37 return rv38 39 def push(self, data=None):40 """41 Push one layer to the stack. Layer must be a dict or omitted.42 """43 data = data or {}42- self.stack.append(data)44+ self._push(data)45 self.current = self.stack[-1]46 return data47 48 def __getitem__(self, name):50 unmodified linesmodified:jinja/_speedups.c+92 added
20 unmodified lines21 #include <structmember.h>22 23 /* Set by init_constants to real values */24 static PyObject *Undefined, *Deferred, *TemplateRuntimeError;25+static Py_UNICODE *amp, *lt, *gt, *qt;26 27 /**28 * Internal struct used by BaseContext to store the29 * stacked namespaces.32 unmodified lines62 }63 Undefined = PyObject_GetAttrString(datastructure, "Undefined");64 Deferred = PyObject_GetAttrString(datastructure, "Deferred");65 TemplateRuntimeError = PyObject_GetAttrString(exceptions, "TemplateRuntimeError");66+67+ amp = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&", 5, NULL))->str;68+ lt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("<", 4, NULL))->str;69+ gt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(">", 4, NULL))->str;70+ qt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(""", 5, NULL))->str;71+72 Py_DECREF(datastructure);73 Py_DECREF(exceptions);74 return 1;75 }76 77 /**78+ * SGML/XML escape something.79+ *80+ * XXX: this is awefully slow for non unicode objects because they81+ * get converted to unicode first.82+ */83+static PyObject*84+escape(PyObject *self, PyObject *args)85+{86+ PyUnicodeObject *in, *out;87+ Py_UNICODE *outp;88+ int i, len;89+90+ int quotes = 0;91+ PyObject *text = NULL;92+93+ if (!PyArg_ParseTuple(args, "O|b", &text, "es))94+ return NULL;95+ in = (PyUnicodeObject*)PyObject_Unicode(text);96+ if (!in)97+ return NULL;98+99+ /* First we need to figure out how long the escaped string will be */100+ len = 0;101+ for (i = 0;i < in->length; i++) {102+ switch (in->str[i]) {103+ case '&':104+ len += 5;105+ break;106+ case '"':107+ len += quotes ? 5 : 1;108+ break;109+ case '<':110+ case '>':111+ len += 4;112+ break;113+ default:114+ len++;115+ }116+ }117+118+ /* Do we need to escape anything at all? */119+ if (len == in->length) {120+ Py_INCREF(in);121+ return (PyObject*)in;122+ }123+ out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, len);124+ if (!out) {125+ return NULL;126+ }127+128+ outp = out->str;129+ for (i = 0;i < in->length; i++) {130+ switch (in->str[i]) {131+ case '&':132+ Py_UNICODE_COPY(outp, amp, 5);133+ outp += 5;134+ break;135+ case '"':136+ if (quotes) {137+ Py_UNICODE_COPY(outp, qt, 5);138+ outp += 5;139+ }140+ else141+ *outp++ = in->str[i];142+ break;143+ case '<':144+ Py_UNICODE_COPY(outp, lt, 4);145+ outp += 4;146+ break;147+ case '>':148+ Py_UNICODE_COPY(outp, gt, 4);149+ outp += 4;150+ break;151+ default:152+ *outp++ = in->str[i];153+ };154+ }155+156+ return (PyObject*)out;157+}158+159+/**160 * Deallocator for BaseContext.161 *162 * Frees the memory for the stack layers before freeing the object.163 */362 unmodified lines526 PyType_GenericNew /* tp_new */527 };528 529 static PyMethodDef module_methods[] = {530+ {"escape", (PyCFunction)escape, METH_VARARGS,531+ "escape(s, quotes=False) -> string\n\n"532+ "SGML/XML a string."},533 {NULL, NULL, 0, NULL} /* Sentinel */534 };535 536 #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */20 unmodified linesmodified:jinja/environment.py+6 added-4 removed
195 unmodified lines196 __traceback_hide__ = True197 raise_syntax_error(e, self, source)198 else:199 # everything went well. attach the source and return it200- # attach the source for debugging200+ # the attached source is used by the traceback system for201+ # debugging porposes202 rv._source = source203 return rv204 205 def get_template(self, filename):45 unmodified lines251 def apply_filters(self, value, context, filters):252 """253 Apply a list of filters on the variable.254 """255+ cache = context.cache256 for key in filters:255- if key in context.cache:256- func = context.cache[key]257+ if key in cache:258+ func = cache[key]259 else:260 filtername, args = key261 if filtername not in self.filters:262 raise FilterNotFound(filtername)261- context.cache[key] = func = self.filters[filtername](*args)263+ cache[key] = func = self.filters[filtername](*args)264 value = func(self, context, value)265 return value266 267 def perform_test(self, context, testname, args, value, invert):83 unmodified linesmodified:jinja/filters.py+4 added-1 removed
112 unmodified lines113 if isinstance(s, TemplateData):114 return s115 elif hasattr(s, '__html__'):116 return s.__html__()117+ #: small speedup118+ if s.__class__ is not unicode:119+ s = env.to_unicode(s)117- return e(env.to_unicode(s), attribute)120+ return e(s, attribute)121 return wrapped122 123 124 def do_xmlattr():734 unmodified linesmodified:jinja/utils.py+9 added-4 removed
12 unmodified lines13 """14 import re15 import sys16 import string17-import cgi17 from types import MethodType, FunctionType18 from compiler.ast import CallFunc, Name, Const19 from jinja.nodes import Trans20 from jinja.datastructure import Context, Flush28 unmodified lines49 50 #: used by from_string as cache51 _from_string_env = None52 54-escape = cgi.escape55-56-53 def urlize(text, trim_url_limit=None, nofollow=False):54 """55 Converts any URLs in text into clickable links. Works on http://,56 https:// and www. links. Links can have trailing punctuation (periods,584 unmodified lines641 rv = CacheDict(self.capacity)642 rv._mapping = deepcopy(self._mapping)643 rv._queue = deepcopy(self._queue)644 return rv645+646+647+# escaping function. Use this only if you escape unicode648+# objects. in all other cases it's likely that the cgi.escape649+# function performs better.650+try:651+ from jinja._speedups import escape652+except ImportError:653+ from cgi import escape