2015-02-20 06:20:27 +08:00
|
|
|
from contextlib import contextmanager
|
2015-01-28 20:35:27 +08:00
|
|
|
from copy import copy
|
2014-12-15 00:48:51 +08:00
|
|
|
|
2014-11-15 20:54:53 +08:00
|
|
|
# Hard-coded processor for easier use of CSRF protection.
|
2014-12-03 06:23:51 +08:00
|
|
|
_builtin_context_processors = ('django.template.context_processors.csrf',)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class ContextPopException(Exception):
|
|
|
|
"pop() has been called more times than push()"
|
|
|
|
pass
|
|
|
|
|
2013-07-16 19:11:32 +08:00
|
|
|
|
|
|
|
class ContextDict(dict):
|
|
|
|
def __init__(self, context, *args, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2013-07-16 19:11:32 +08:00
|
|
|
|
|
|
|
context.dicts.append(self)
|
|
|
|
self.context = context
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, *args, **kwargs):
|
|
|
|
self.context.pop()
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BaseContext:
|
2009-12-14 20:08:23 +08:00
|
|
|
def __init__(self, dict_=None):
|
2011-04-17 12:52:31 +08:00
|
|
|
self._reset_dicts(dict_)
|
|
|
|
|
|
|
|
def _reset_dicts(self, value=None):
|
2012-04-11 04:49:45 +08:00
|
|
|
builtins = {'True': True, 'False': False, 'None': None}
|
|
|
|
self.dicts = [builtins]
|
2012-04-11 21:00:38 +08:00
|
|
|
if value is not None:
|
|
|
|
self.dicts.append(value)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-02-21 18:12:23 +08:00
|
|
|
def __copy__(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
duplicate = copy(super())
|
2011-04-17 12:52:31 +08:00
|
|
|
duplicate.dicts = self.dicts[:]
|
2011-02-21 18:12:23 +08:00
|
|
|
return duplicate
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return repr(self.dicts)
|
|
|
|
|
|
|
|
def __iter__(self):
|
2009-12-14 20:08:23 +08:00
|
|
|
for d in reversed(self.dicts):
|
2006-05-02 09:31:56 +08:00
|
|
|
yield d
|
|
|
|
|
2013-07-16 19:11:32 +08:00
|
|
|
def push(self, *args, **kwargs):
|
2015-09-11 04:54:19 +08:00
|
|
|
dicts = []
|
|
|
|
for d in args:
|
|
|
|
if isinstance(d, BaseContext):
|
|
|
|
dicts += d.dicts[1:]
|
|
|
|
else:
|
|
|
|
dicts.append(d)
|
|
|
|
return ContextDict(self, *dicts, **kwargs)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def pop(self):
|
|
|
|
if len(self.dicts) == 1:
|
|
|
|
raise ContextPopException
|
2009-12-14 20:08:23 +08:00
|
|
|
return self.dicts.pop()
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
"Set a variable in the current context"
|
2009-12-14 20:08:23 +08:00
|
|
|
self.dicts[-1][key] = value
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2016-07-17 04:55:40 +08:00
|
|
|
def set_upward(self, key, value):
|
|
|
|
"""
|
|
|
|
Set a variable in one of the higher contexts if it exists there,
|
|
|
|
otherwise in the current context.
|
|
|
|
"""
|
|
|
|
context = self.dicts[-1]
|
|
|
|
for d in reversed(self.dicts):
|
|
|
|
if key in d.keys():
|
|
|
|
context = d
|
|
|
|
break
|
|
|
|
context[key] = value
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def __getitem__(self, key):
|
|
|
|
"Get a variable's value, starting at the current context and going upward"
|
2009-12-14 20:08:23 +08:00
|
|
|
for d in reversed(self.dicts):
|
2007-04-26 21:30:48 +08:00
|
|
|
if key in d:
|
2006-05-02 09:31:56 +08:00
|
|
|
return d[key]
|
2006-07-04 11:21:44 +08:00
|
|
|
raise KeyError(key)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
"Delete a variable from the current context"
|
2009-12-14 20:08:23 +08:00
|
|
|
del self.dicts[-1][key]
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2016-02-23 02:25:01 +08:00
|
|
|
def __contains__(self, key):
|
2006-05-02 09:31:56 +08:00
|
|
|
for d in self.dicts:
|
2007-04-26 21:30:48 +08:00
|
|
|
if key in d:
|
2006-05-02 09:31:56 +08:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2006-07-04 11:21:44 +08:00
|
|
|
def get(self, key, otherwise=None):
|
2009-12-14 20:08:23 +08:00
|
|
|
for d in reversed(self.dicts):
|
2007-04-26 21:30:48 +08:00
|
|
|
if key in d:
|
2006-05-02 09:31:56 +08:00
|
|
|
return d[key]
|
|
|
|
return otherwise
|
|
|
|
|
2015-03-12 00:00:17 +08:00
|
|
|
def setdefault(self, key, default=None):
|
|
|
|
try:
|
|
|
|
return self[key]
|
|
|
|
except KeyError:
|
|
|
|
self[key] = default
|
|
|
|
return default
|
|
|
|
|
2011-04-17 12:52:31 +08:00
|
|
|
def new(self, values=None):
|
|
|
|
"""
|
|
|
|
Returns a new context with the same properties, but with only the
|
|
|
|
values given in 'values' stored.
|
|
|
|
"""
|
|
|
|
new_context = copy(self)
|
|
|
|
new_context._reset_dicts(values)
|
|
|
|
return new_context
|
|
|
|
|
2014-02-16 21:50:27 +08:00
|
|
|
def flatten(self):
|
|
|
|
"""
|
|
|
|
Returns self.dicts as one dictionary
|
|
|
|
"""
|
|
|
|
flat = {}
|
|
|
|
for d in self.dicts:
|
|
|
|
flat.update(d)
|
|
|
|
return flat
|
|
|
|
|
2014-02-15 20:45:52 +08:00
|
|
|
def __eq__(self, other):
|
|
|
|
"""
|
|
|
|
Compares two contexts by comparing theirs 'dicts' attributes.
|
|
|
|
"""
|
|
|
|
if isinstance(other, BaseContext):
|
2014-02-16 05:58:03 +08:00
|
|
|
# because dictionaries can be put in different order
|
|
|
|
# we have to flatten them like in templates
|
2014-02-16 21:50:27 +08:00
|
|
|
return self.flatten() == other.flatten()
|
2014-02-15 20:45:52 +08:00
|
|
|
|
|
|
|
# if it's not comparable return false
|
|
|
|
return False
|
|
|
|
|
2013-07-16 19:11:32 +08:00
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
class Context(BaseContext):
|
|
|
|
"A stack container for variable context"
|
2015-09-04 03:52:04 +08:00
|
|
|
def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None):
|
2009-12-14 20:08:23 +08:00
|
|
|
self.autoescape = autoescape
|
2011-11-18 21:01:06 +08:00
|
|
|
self.use_l10n = use_l10n
|
|
|
|
self.use_tz = use_tz
|
2014-04-15 05:18:03 +08:00
|
|
|
self.template_name = "unknown"
|
2009-12-14 20:08:23 +08:00
|
|
|
self.render_context = RenderContext()
|
2015-02-20 06:20:27 +08:00
|
|
|
# Set to the original template -- as opposed to extended or included
|
|
|
|
# templates -- during rendering, see bind_template.
|
2015-02-18 05:49:59 +08:00
|
|
|
self.template = None
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(dict_)
|
2009-12-14 20:08:23 +08:00
|
|
|
|
2015-02-20 06:20:27 +08:00
|
|
|
@contextmanager
|
|
|
|
def bind_template(self, template):
|
|
|
|
if self.template is not None:
|
|
|
|
raise RuntimeError("Context is already bound to a template")
|
|
|
|
self.template = template
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self.template = None
|
|
|
|
|
2011-02-21 18:12:23 +08:00
|
|
|
def __copy__(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
duplicate = super().__copy__()
|
2011-02-21 18:12:23 +08:00
|
|
|
duplicate.render_context = copy(self.render_context)
|
|
|
|
return duplicate
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def update(self, other_dict):
|
2010-11-24 08:36:36 +08:00
|
|
|
"Pushes other_dict to the stack of dictionaries in the Context"
|
2009-03-19 00:55:59 +08:00
|
|
|
if not hasattr(other_dict, '__getitem__'):
|
2008-08-02 05:37:38 +08:00
|
|
|
raise TypeError('other_dict must be a mapping (dictionary-like) object.')
|
2015-09-11 04:54:19 +08:00
|
|
|
if isinstance(other_dict, BaseContext):
|
|
|
|
other_dict = other_dict.dicts[1:].pop()
|
2015-04-13 22:57:44 +08:00
|
|
|
return ContextDict(self, other_dict)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-07-16 19:11:32 +08:00
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
class RenderContext(BaseContext):
|
|
|
|
"""
|
|
|
|
A stack container for storing Template state.
|
|
|
|
|
|
|
|
RenderContext simplifies the implementation of template Nodes by providing a
|
|
|
|
safe place to store state between invocations of a node's `render` method.
|
|
|
|
|
|
|
|
The RenderContext also provides scoping rules that are more sensible for
|
|
|
|
'template local' variables. The render context stack is pushed before each
|
|
|
|
template is rendered, creating a fresh scope with nothing in it. Name
|
|
|
|
resolution fails if a variable is not found at the top of the RequestContext
|
|
|
|
stack. Thus, variables are local to a specific template and don't affect the
|
|
|
|
rendering of other templates as they would if they were stored in the normal
|
|
|
|
template context.
|
|
|
|
"""
|
2016-12-14 10:35:21 +08:00
|
|
|
template = None
|
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
def __iter__(self):
|
|
|
|
for d in self.dicts[-1]:
|
|
|
|
yield d
|
|
|
|
|
2016-02-23 02:25:01 +08:00
|
|
|
def __contains__(self, key):
|
2009-12-14 20:08:23 +08:00
|
|
|
return key in self.dicts[-1]
|
|
|
|
|
|
|
|
def get(self, key, otherwise=None):
|
2013-12-19 13:42:32 +08:00
|
|
|
return self.dicts[-1].get(key, otherwise)
|
2009-12-14 20:08:23 +08:00
|
|
|
|
2013-12-19 13:42:32 +08:00
|
|
|
def __getitem__(self, key):
|
|
|
|
return self.dicts[-1][key]
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2016-12-14 10:35:21 +08:00
|
|
|
@contextmanager
|
|
|
|
def push_state(self, template):
|
|
|
|
initial = self.template
|
|
|
|
self.template = template
|
|
|
|
self.push()
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self.template = initial
|
|
|
|
self.pop()
|
|
|
|
|
2013-12-20 12:43:34 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class RequestContext(Context):
|
|
|
|
"""
|
|
|
|
This subclass of template.Context automatically populates itself using
|
2014-12-18 06:36:32 +08:00
|
|
|
the processors defined in the engine's configuration.
|
2006-05-02 09:31:56 +08:00
|
|
|
Additional processors can be specified as a list of callables
|
|
|
|
using the "processors" keyword argument.
|
|
|
|
"""
|
2015-11-08 17:06:07 +08:00
|
|
|
def __init__(self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape)
|
2014-12-15 00:48:51 +08:00
|
|
|
self.request = request
|
2014-11-21 05:34:59 +08:00
|
|
|
self._processors = () if processors is None else tuple(processors)
|
|
|
|
self._processors_index = len(self.dicts)
|
2015-05-27 03:38:01 +08:00
|
|
|
|
|
|
|
# placeholder for context processors output
|
|
|
|
self.update({})
|
|
|
|
|
|
|
|
# empty dict for any new modifications
|
|
|
|
# (so that context processors don't overwrite them)
|
|
|
|
self.update({})
|
2014-11-21 05:34:59 +08:00
|
|
|
|
2015-02-20 06:20:27 +08:00
|
|
|
@contextmanager
|
|
|
|
def bind_template(self, template):
|
|
|
|
if self.template is not None:
|
|
|
|
raise RuntimeError("Context is already bound to a template")
|
|
|
|
|
|
|
|
self.template = template
|
|
|
|
# Set context processors according to the template engine's settings.
|
|
|
|
processors = (template.engine.template_context_processors +
|
|
|
|
self._processors)
|
|
|
|
updates = {}
|
|
|
|
for processor in processors:
|
|
|
|
updates.update(processor(self.request))
|
|
|
|
self.dicts[self._processors_index] = updates
|
|
|
|
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self.template = None
|
|
|
|
# Unset context processors.
|
|
|
|
self.dicts[self._processors_index] = {}
|
2014-11-21 05:34:59 +08:00
|
|
|
|
|
|
|
def new(self, values=None):
|
2017-01-21 21:13:44 +08:00
|
|
|
new_context = super().new(values)
|
2014-11-21 05:34:59 +08:00
|
|
|
# This is for backwards-compatibility: RequestContexts created via
|
|
|
|
# Context.new don't include values from context processors.
|
2015-02-05 20:20:33 +08:00
|
|
|
if hasattr(new_context, '_processors_index'):
|
|
|
|
del new_context._processors_index
|
2014-11-21 05:34:59 +08:00
|
|
|
return new_context
|
2015-02-10 17:29:00 +08:00
|
|
|
|
|
|
|
|
2015-11-08 17:06:07 +08:00
|
|
|
def make_context(context, request=None, **kwargs):
|
2015-02-10 17:29:00 +08:00
|
|
|
"""
|
|
|
|
Create a suitable Context from a plain dict and optionally an HttpRequest.
|
|
|
|
"""
|
2016-12-29 05:03:20 +08:00
|
|
|
if context is not None and not isinstance(context, dict):
|
|
|
|
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
|
2015-02-10 17:29:00 +08:00
|
|
|
if request is None:
|
2015-11-08 17:06:07 +08:00
|
|
|
context = Context(context, **kwargs)
|
2015-02-10 17:29:00 +08:00
|
|
|
else:
|
|
|
|
# The following pattern is required to ensure values from
|
|
|
|
# context override those from template context processors.
|
|
|
|
original_context = context
|
2015-11-08 17:06:07 +08:00
|
|
|
context = RequestContext(request, **kwargs)
|
2015-02-10 17:29:00 +08:00
|
|
|
if original_context:
|
|
|
|
context.push(original_context)
|
|
|
|
return context
|