Updated mako lib

This commit is contained in:
rembo10
2014-03-31 21:50:41 -07:00
parent 708f5fcd70
commit 0c714a78de
22 changed files with 570 additions and 318 deletions
+81 -40
View File
@@ -1,5 +1,5 @@
# mako/runtime.py
# Copyright (C) 2006-2012 the Mako authors and contributors <see AUTHORS file>
# Copyright (C) 2006-2013 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
@@ -7,8 +7,11 @@
"""provides runtime services for templates, including Context,
Namespace, and various helper functions."""
from mako import exceptions, util
import __builtin__, inspect, sys
from mako import exceptions, util, compat
from mako.compat import compat_builtins
import inspect
import sys
import collections
class Context(object):
@@ -32,7 +35,7 @@ class Context(object):
# "capture" function which proxies to the
# generic "capture" function
self._data['capture'] = util.partial(capture, self)
self._data['capture'] = compat.partial(capture, self)
# "caller" stack used by def calls with content
self.caller_stack = self._data['caller'] = CallerStack()
@@ -55,8 +58,22 @@ class Context(object):
@property
def kwargs(self):
"""Return the dictionary of keyword arguments associated with this
:class:`.Context`.
"""Return the dictionary of top level keyword arguments associated
with this :class:`.Context`.
This dictionary only includes the top-level arguments passed to
:meth:`.Template.render`. It does not include names produced within
the template execution such as local variable names or special names
such as ``self``, ``next``, etc.
The purpose of this dictionary is primarily for the case that
a :class:`.Template` accepts arguments via its ``<%page>`` tag,
which are normally expected to be passed via :meth:`.Template.render`,
except the template is being called in an inheritance context,
using the ``body()`` method. :attr:`.Context.kwargs` can then be
used to propagate these arguments to the inheriting template::
${next.body(**context.kwargs)}
"""
return self._kwargs.copy()
@@ -77,13 +94,13 @@ class Context(object):
def keys(self):
"""Return a list of all names established in this :class:`.Context`."""
return self._data.keys()
return list(self._data.keys())
def __getitem__(self, key):
if key in self._data:
return self._data[key]
else:
return __builtin__.__dict__[key]
return compat_builtins.__dict__[key]
def _push_writer(self):
"""push a capturing buffer onto this Context and return
@@ -116,7 +133,7 @@ class Context(object):
"""Return a value from this :class:`.Context`."""
return self._data.get(key,
__builtin__.__dict__.get(key, default)
compat_builtins.__dict__.get(key, default)
)
def write(self, string):
@@ -141,11 +158,18 @@ class Context(object):
c.caller_stack = self.caller_stack
return c
def locals_(self, d):
def _locals(self, d):
"""Create a new :class:`.Context` with a copy of this
:class:`.Context`'s current state, updated with the given dictionary."""
:class:`.Context`'s current state,
updated with the given dictionary.
if len(d) == 0:
The :attr:`.Context.kwargs` collection remains
unaffected.
"""
if not d:
return self
c = self._copy()
c._data.update(d)
@@ -165,19 +189,27 @@ class Context(object):
class CallerStack(list):
def __init__(self):
self.nextcaller = None
def __nonzero__(self):
return self._get_caller() and True or False
return self.__bool__()
def __bool__(self):
return len(self) and self._get_caller() and True or False
def _get_caller(self):
# this method can be removed once
# codegen MAGIC_NUMBER moves past 7
return self[-1]
def __getattr__(self, key):
return getattr(self._get_caller(), key)
def _push_frame(self):
frame = self.nextcaller or None
self.append(frame)
self.nextcaller = None
return frame
def _pop_frame(self):
self.nextcaller = self.pop()
@@ -192,7 +224,11 @@ class Undefined(object):
"""
def __str__(self):
raise NameError("Undefined")
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
return False
UNDEFINED = Undefined()
@@ -336,7 +372,7 @@ class Namespace(object):
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
self.callables = dict([(c.__name__, c) for c in callables])
callables = ()
@@ -394,8 +430,13 @@ class Namespace(object):
This accessor allows templates to supply "scalar"
attributes which are particularly handy in inheritance
relationships. See the example in
:ref:`inheritance_toplevel`.
relationships.
.. seealso::
:ref:`inheritance_attr`
:ref:`namespace_attr_for_includes`
"""
return _NSAttr(self)
@@ -502,7 +543,7 @@ class TemplateNamespace(Namespace):
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
self.callables = dict([(c.__name__, c) for c in callables])
if templateuri is not None:
self.template = _lookup_template(context, templateuri,
@@ -554,7 +595,7 @@ class TemplateNamespace(Namespace):
yield (key, self.callables[key])
def get(key):
callable_ = self.template._get_def_callable(key)
return util.partial(callable_, self.context)
return compat.partial(callable_, self.context)
for k in self.template.module._exports:
yield (k, get(k))
@@ -563,7 +604,7 @@ class TemplateNamespace(Namespace):
val = self.callables[key]
elif self.template.has_def(key):
callable_ = self.template._get_def_callable(key)
val = util.partial(callable_, self.context)
val = compat.partial(callable_, self.context)
elif self.inherits:
val = getattr(self.inherits, key)
@@ -584,7 +625,7 @@ class ModuleNamespace(Namespace):
self.context = context
self.inherits = inherits
if callables is not None:
self.callables = dict([(c.func_name, c) for c in callables])
self.callables = dict([(c.__name__, c) for c in callables])
mod = __import__(module)
for token in module.split('.')[1:]:
@@ -602,19 +643,19 @@ class ModuleNamespace(Namespace):
if self.callables:
for key in self.callables:
yield (key, self.callables[key])
def get(key):
callable_ = getattr(self.module, key)
return util.partial(callable_, self.context)
for k in dir(self.module):
if k[0] != '_':
yield (k, get(k))
for key in dir(self.module):
if key[0] != '_':
callable_ = getattr(self.module, key)
if compat.callable(callable_):
yield key, compat.partial(callable_, self.context)
def __getattr__(self, key):
if key in self.callables:
val = self.callables[key]
elif hasattr(self.module, key):
callable_ = getattr(self.module, key)
val = util.partial(callable_, self.context)
val = compat.partial(callable_, self.context)
elif self.inherits:
val = getattr(self.inherits, key)
else:
@@ -648,7 +689,7 @@ def capture(context, callable_, *args, **kwargs):
"""
if not callable(callable_):
if not compat.callable(callable_):
raise exceptions.RuntimeException(
"capture() function expects a callable as "
"its argument (i.e. capture(func, *args, **kwargs))"
@@ -704,10 +745,10 @@ def _inherit_from(context, uri, calling_uri):
ih = self_ns
while ih.inherits is not None:
ih = ih.inherits
lclcontext = context.locals_({'next':ih})
lclcontext = context._locals({'next': ih})
ih.inherits = TemplateNamespace("self:%s" % template.uri,
lclcontext,
template = template,
template=template,
populate_self=False)
context._data['parent'] = lclcontext._data['local'] = ih.inherits
callable_ = getattr(template.module, '_mako_inherit', None)
@@ -730,8 +771,8 @@ def _lookup_template(context, uri, relativeto):
uri = lookup.adjust_uri(uri, relativeto)
try:
return lookup.get_template(uri)
except exceptions.TopLevelLookupException, e:
raise exceptions.TemplateLookupException(str(e))
except exceptions.TopLevelLookupException:
raise exceptions.TemplateLookupException(str(compat.exception_as()))
def _populate_self_namespace(context, template, self_ns=None):
if self_ns is None:
@@ -750,12 +791,12 @@ def _render(template, callable_, args, data, as_unicode=False):
output of the given template and template callable."""
if as_unicode:
buf = util.FastEncodingBuffer(unicode=True)
buf = util.FastEncodingBuffer(as_unicode=True)
elif template.bytestring_passthrough:
buf = util.StringIO()
buf = compat.StringIO()
else:
buf = util.FastEncodingBuffer(
unicode=as_unicode,
as_unicode=as_unicode,
encoding=template.output_encoding,
errors=template.encoding_errors)
context = Context(buf, **data)
@@ -767,7 +808,7 @@ def _render(template, callable_, args, data, as_unicode=False):
return context._pop_buffer().getvalue()
def _kwargs_for_callable(callable_, data):
argspec = util.inspect_func_args(callable_)
argspec = compat.inspect_func_args(callable_)
# for normal pages, **pageargs is usually present
if argspec[2]:
return data
@@ -781,7 +822,7 @@ def _kwargs_for_callable(callable_, data):
return kwargs
def _kwargs_for_include(callable_, data, **kwargs):
argspec = util.inspect_func_args(callable_)
argspec = compat.inspect_func_args(callable_)
namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None]
for arg in namedargs:
if arg != 'context' and arg in data and arg not in kwargs:
@@ -815,8 +856,8 @@ def _exec_template(callable_, context, args=None, kwargs=None):
error = None
try:
callable_(context, *args, **kwargs)
except Exception, e:
_render_error(template, context, e)
except Exception:
_render_error(template, context, compat.exception_as())
except:
e = sys.exc_info()[0]
_render_error(template, context, e)
@@ -831,7 +872,7 @@ def _render_error(template, context, error):
else:
error_template = exceptions.html_error_template()
if context._outputting_as_unicode:
context._buffer_stack[:] = [util.FastEncodingBuffer(unicode=True)]
context._buffer_stack[:] = [util.FastEncodingBuffer(as_unicode=True)]
else:
context._buffer_stack[:] = [util.FastEncodingBuffer(
error_template.output_encoding,