Skip to content
Myr

[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

5 files+115 added−11 removed

modified:jinja/_native.py+4 added-2 removed
21 unmodified lines
22 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 = initial3031 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 rv3839 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 data4748 def __getitem__(self, name):
50 unmodified lines
modified:jinja/_speedups.c+92 added
20 unmodified lines
21#include <structmember.h>2223/* Set by init_constants to real values */24static PyObject *Undefined, *Deferred, *TemplateRuntimeError;25static Py_UNICODE *amp, *lt, *gt, *qt;2627/**28 * Internal struct used by BaseContext to store the29 * stacked namespaces.
32 unmodified lines
62 }63 Undefined = PyObject_GetAttrString(datastructure, "Undefined");64 Deferred = PyObject_GetAttrString(datastructure, "Deferred");65 TemplateRuntimeError = PyObject_GetAttrString(exceptions, "TemplateRuntimeError");6667 amp = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&amp;", 5, NULL))->str;68 lt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&lt;", 4, NULL))->str;69 gt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&gt;", 4, NULL))->str;70 qt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&#34;", 5, NULL))->str;7172 Py_DECREF(datastructure);73 Py_DECREF(exceptions);74 return 1;75}7677/**78 * SGML/XML escape something.79 *80 * XXX: this is awefully slow for non unicode objects because they81 * get converted to unicode first.82 */83static PyObject*84escape(PyObject *self, PyObject *args)85{86 PyUnicodeObject *in, *out;87 Py_UNICODE *outp;88 int i, len;8990 int quotes = 0;91 PyObject *text = NULL;9293 if (!PyArg_ParseTuple(args, "O|b", &text, &quotes))94 return NULL;95 in = (PyUnicodeObject*)PyObject_Unicode(text);96 if (!in)97 return NULL;9899 /* 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 }117118 /* 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 }127128 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 }155156 return (PyObject*)out;157}158159/**160 * Deallocator for BaseContext.161 *162 * Frees the memory for the stack layers before freeing the object.163 */
362 unmodified lines
526 PyType_GenericNew /* tp_new */527};528529static 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};535536#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
20 unmodified lines
modified:jinja/environment.py+6 added-4 removed
195 unmodified lines
196 __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 rv204205 def get_template(self, filename):
45 unmodified lines
251 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 value266267 def perform_test(self, context, testname, args, value, invert):
83 unmodified lines
modified:jinja/filters.py+4 added-1 removed
112 unmodified lines
113 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 wrapped122123124def do_xmlattr():
734 unmodified lines
modified:jinja/utils.py+9 added-4 removed
12 unmodified lines
13"""14import re15import sys16import string17import cgi17from types import MethodType, FunctionType18from compiler.ast import CallFunc, Name, Const19from jinja.nodes import Trans20from jinja.datastructure import Context, Flush
28 unmodified lines
4950#: used by from_string as cache51_from_string_env = None5254escape = cgi.escape555653def 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 lines
641 rv = CacheDict(self.capacity)642 rv._mapping = deepcopy(self._mapping)643 rv._queue = deepcopy(self._queue)644 return rv645646647# escaping function. Use this only if you escape unicode648# objects. in all other cases it's likely that the cgi.escape649# function performs better.650try:651 from jinja._speedups import escape652except ImportError:653 from cgi import escape