simplified loader api and added builtin caching
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 68f7767 · Browse files · 6 files·+215 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+215 added−43 removed
- other:+215 added−43 removed
Provenance
- Commit
814f6c2- Tree
3062f82- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
68f7767
6 files changed+215 added−43 removed
modified:jinja2/__init__.py+1 added
55 unmodified lines56 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58 """59 from jinja2.environment import Environment60+from jinja2.loaders import BaseLoader, FileSystemLoader, DictLoader61 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined62 from jinja2.utils import Markup, escapemodified:jinja2/defaults.py+1 added
13 unmodified lines14 15 DEFAULT_NAMESPACE = {16 'range': xrange,17 # fake translators so that {% trans %} is a noop by default18+ '_': lambda x: x,19 'gettext': lambda x: x,20 'ngettext': lambda s, p, n: (s, p)[n != 1]21 }modified:jinja2/environment.py+10 added-3 removed
128 unmodified lines129 The tuples are returned in the form ``(lineno, token, value)``.130 """131 return self.lexer.tokeniter(source, name)132 133- def compile(self, source, name=None, filename=None, raw=False,134- globals=None):133+ def compile(self, source, name=None, filename=None, globals=None,134+ raw=False):135 """Compile a node or source. The name is the load name of the136 template after it was joined using `join_path` if necessary,137 filename is the estimated filename of the template on the file138 system. If the template came from a database or memory this42 unmodified lines181 182 class Template(object):183 """Represents a template."""184 185- def __init__(self, environment, code, globals):185+ def __init__(self, environment, code, globals, uptodate=None):186 namespace = {'environment': environment}187 exec code in namespace188 self.environment = environment189 self.name = namespace['name']3 unmodified lines193 self.globals = globals194 195 # debug helpers196 self._get_debug_info = namespace['get_debug_info']197+ self._uptodate = uptodate198 namespace['__jinja_template__'] = self199 200 def render(self, *args, **kwargs):201 return u''.join(self.generate(*args, **kwargs))37 unmodified lines239 if code_line <= lineno:240 return template_line241 return 1242 243+ def is_up_to_date(self):244+ """Check if the template is still up to date."""245+ if self._uptodate is None:246+ return True247+ return self._uptodate()248+249 def __repr__(self):250 return '<%s %r>' % (251 self.__class__.__name__,252 self.name48 unmodified linesmodified:jinja2/filters.py+7 added-23 removed
19 unmodified lines20 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode21 from jinja2.runtime import Undefined22 23 24-24 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')25 26 27 def contextfilter(f):50 unmodified lines78 """Convert a value to lowercase."""79 return soft_unicode(s).lower()80 81 83-def do_escape(s):84- """XML escape ``&``, ``<``, ``>``, and ``"`` in a string of data.85-86- This method will have no effect it the value is already escaped.87- """88- return escape(s)89-90-82 def do_xmlattr(d, autospace=False):83 """Create an SGML/XML attribute string based on the items in a dict.84 All values that are neither `none` nor `undefined` are automatically85 escaped:304 unmodified lines390 """391 try:392 return int(value)393 except (TypeError, ValueError):403- try:404- return int(float(value))405- except (TypeError, ValueError):406- return default394+ return default395 396 397 def do_float(value, default=0.0):398 """Convert the value into a floating point number. If the56 unmodified lines455 456 If you pass it a second argument it's used to fill missing457 values on the last iteration.458 """471- result = []472- seq = list(value)459+ seq = list(seq)460 length = len(seq)461 items_per_slice = length // slices462 slices_with_extra = length % slices463 offset = 04 unmodified lines468 end = offset + (slice_number + 1) * items_per_slice469 tmp = seq[start:end]470 if fill_with is not None and slice_number >= slices_with_extra:471 tmp.append(fill_with)485- result.append(tmp)486- return result472+ yield tmp473 474 475 def do_batch(value, linecount, fill_with=None):476 """17 unmodified lines494 result = []495 tmp = []496 for item in value:497 if len(tmp) == linecount:512- result.append(tmp)498+ yield tmp499 tmp = []500 tmp.append(item)501 if tmp:502 if fill_with is not None and len(tmp) < linecount:503 tmp += [fill_with] * (linecount - len(tmp))518- result.append(tmp)519- return result504+ yield tmp505 506 507 def do_round(value, precision=0, method='common'):508 """Round the number to a given precision. The first69 unmodified lines578 FILTERS = {579 'replace': do_replace,580 'upper': do_upper,581 'lower': do_lower,597- 'escape': do_escape,598- 'e': do_escape,582+ 'escape': escape,583+ 'e': escape,584 'xmlattr': do_xmlattr,585 'capitalize': do_capitalize,586 'title': do_title,587 'default': do_default,9 unmodified lines597 'last': do_last,598 'random': do_random,599 'filesizeformat': do_filesizeformat,600 'pprint': do_pprint,616- 'indent': do_indent,601 'truncate': do_truncate,602 'wordwrap': do_wordwrap,603 'wordcount': do_wordcount,604 'int': do_int,15 unmodified linesmodified:jinja2/loaders.py+75 added-17 removed
7 unmodified lines8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from os import path12+from time import time13 from jinja2.exceptions import TemplateNotFound14 from jinja2.environment import Template15+from jinja2.utils import LRUCache16 17 18 class BaseLoader(object):17- """Baseclass for all loaders."""19+ """20+ Baseclass for all loaders. Subclass this and override `get_source` to21+ implement a custom loading mechanism.22 23+ The environment provides a `get_template` method that will automatically24+ call the loader bound to an environment.25+ """26+27+ def __init__(self, cache_size=50, auto_reload=True):28+ if cache_size > 0:29+ self.cache = LRUCache(cache_size)30+ else:31+ self.cache = None32+ self.auto_reload = auto_reload33+34 def get_source(self, environment, template):20- raise TemplateNotFound()35+ """Get the template source, filename and reload helper for a template.36+ It's passed the environment and template name and has to return a37+ tuple in the form ``(source, filename, uptodate)`` or raise a38+ `TemplateNotFound` error if it can't locate the template.39 40+ The source part of the returned tuple must be the source of the41+ template as unicode string or a ASCII bytestring. The filename should42+ be the name of the file on the filesystem if it was loaded from there,43+ otherwise `None`. The filename is used by python for the tracebacks44+ if no loader extension is used.45+46+ The last item in the tuple is the `uptodate` function. If auto47+ reloading is enabled it's always called to check if the template48+ changed. No arguments are passed so the function must store the49+ old state somewhere (for example in a closure). If it returns `False`50+ the template will be reloaded.51+ """52+ raise TemplateNotFound(template)53+54 def load(self, environment, name, globals=None):23- source, filename = self.get_source(environment, name)24- code = environment.compile(source, name, filename, globals=globals)25- return Template(environment, code, globals or {})55+ """Loads a template. This method should not be overriden by56+ subclasses unless `get_source` doesn't provide enough flexibility.57+ """58+ if globals is None:59+ globals = {}60 61+ if self.cache is not None:62+ template = self.cache.get(name)63+ if template is not None and (not self.auto_reload or \64+ template.is_up_to_date()):65+ return template66 67+ source, filename, uptodate = self.get_source(environment, name)68+ code = environment.compile(source, name, filename, globals)69+ template = Template(environment, code, globals, uptodate)70+ if self.cache is not None:71+ self.cache[name] = template72+ return template73+74+75 class FileSystemLoader(BaseLoader):76+ """Loads templates from the file system."""77 30- def __init__(self, path, encoding='utf-8'):31- self.path = path78+ def __init__(self, searchpath, encoding='utf-8', cache_size=50,79+ auto_reload=True):80+ BaseLoader.__init__(self, cache_size, auto_reload)81+ if isinstance(searchpath, basestring):82+ searchpath = [searchpath]83+ self.searchpath = searchpath84 self.encoding = encoding85 86 def get_source(self, environment, template):87 pieces = []88 for piece in template.split('/'):89 if piece == '..':38- raise TemplateNotFound()90+ raise TemplateNotFound(template)91 elif piece != '.':92 pieces.append(piece)41- filename = path.join(self.path, *pieces)42- if not path.isfile(filename):43- raise TemplateNotFound(template)44- f = file(filename)45- try:46- return f.read().decode(self.encoding), filename47- finally:48- f.close()93+ for searchpath in self.searchpath:94+ filename = path.join(searchpath, *pieces)95+ if path.isfile(filename):96+ f = file(filename)97+ try:98+ contents = f.read().decode(self.encoding)99+ finally:100+ f.close()101+ mtime = path.getmtime(filename)102+ def uptodate():103+ return path.getmtime(filename) != mtime104+ return contents, filename, uptodate105+ raise TemplateNotFound(template)106 107 108 class DictLoader(BaseLoader):109+ """Loads a template from a python dict. Used for unittests mostly."""110 111 def __init__(self, mapping):112 self.mapping = mapping113 114 def get_source(self, environment, template):115 if template in self.mapping:58- return self.mapping[template], template116+ return self.mapping[template], None, None117 raise TemplateNotFound(template)modified:jinja2/utils.py+121 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import string13+from collections import deque14+from copy import deepcopy15 from functools import update_wrapper16 from itertools import imap17 18 178 unmodified lines197 __str__ = lambda s: str(escape(s.obj))198 __repr__ = lambda s: str(repr(escape(s.obj)))199 __int__ = lambda s: int(s.obj)200 __float__ = lambda s: float(s.obj)201+202+203+class LRUCache(object):204+ """A simple LRU Cache implementation."""205+ # this is fast for small capacities (something around 200) but doesn't206+ # scale. But as long as it's only used for the database connections in207+ # a non request fallback it's fine.208+209+ def __init__(self, capacity):210+ self.capacity = capacity211+ self._mapping = {}212+ self._queue = deque()213+214+ # alias all queue methods for faster lookup215+ self._popleft = self._queue.popleft216+ self._pop = self._queue.pop217+ if hasattr(self._queue, 'remove'):218+ self._remove = self._queue.remove219+ self._append = self._queue.append220+221+ def _remove(self, obj):222+ """Python 2.4 compatibility."""223+ for idx, item in enumerate(self._queue):224+ if item == obj:225+ del self._queue[idx]226+ break227+228+ def copy(self):229+ """Return an shallow copy of the instance."""230+ rv = LRUCache(self.capacity)231+ rv._mapping.update(self._mapping)232+ rv._queue = self._queue[:]233+ return rv234+235+ def get(self, key, default=None):236+ """Return an item from the cache dict or `default`"""237+ if key in self:238+ return self[key]239+ return default240+241+ def setdefault(self, key, default=None):242+ """243+ Set `default` if the key is not in the cache otherwise244+ leave unchanged. Return the value of this key.245+ """246+ if key in self:247+ return self[key]248+ self[key] = default249+ return default250+251+ def clear(self):252+ """Clear the cache."""253+ self._mapping.clear()254+ self._queue.clear()255+256+ def __contains__(self, key):257+ """Check if a key exists in this cache."""258+ return key in self._mapping259+260+ def __len__(self):261+ """Return the current size of the cache."""262+ return len(self._mapping)263+264+ def __repr__(self):265+ return '<%s %r>' % (266+ self.__class__.__name__,267+ self._mapping268+ )269+270+ def __getitem__(self, key):271+ """Get an item from the cache. Moves the item up so that it has the272+ highest priority then.273+274+ Raise an `KeyError` if it does not exist.275+ """276+ rv = self._mapping[key]277+ if self._queue[-1] != key:278+ self._remove(key)279+ self._append(key)280+ return rv281+282+ def __setitem__(self, key, value):283+ """Sets the value for an item. Moves the item up so that it284+ has the highest priority then.285+ """286+ if key in self._mapping:287+ self._remove(key)288+ elif len(self._mapping) == self.capacity:289+ del self._mapping[self._popleft()]290+ self._append(key)291+ self._mapping[key] = value292+293+ def __delitem__(self, key):294+ """Remove an item from the cache dict.295+ Raise an `KeyError` if it does not exist.296+ """297+ del self._mapping[key]298+ self._remove(key)299+300+ def __iter__(self):301+ """Iterate over all values in the cache dict, ordered by302+ the most recent usage.303+ """304+ return reversed(self._queue)305+306+ def __reversed__(self):307+ """Iterate over the values in the cache dict, oldest items308+ coming first.309+ """310+ return iter(self._queue)311+312+ __copy__ = copy313+314+ def __deepcopy__(self):315+ """Return a deep copy of the LRU Cache"""316+ rv = LRUCache(self.capacity)317+ rv._mapping = deepcopy(self._mapping)318+ rv._queue = deepcopy(self._queue)319+ return rv