Debian Codegraph @

django/template/context.py

raw
1 from contextlib import contextmanager
2 from copy import copy
3
4 # Hard-coded processor for easier use of CSRF protection.
5 _builtin_context_processors = ("django.template.context_processors.csrf",)
6
7
8 class ContextPopException(Exception):
9 "pop() has been called more times than push()"
10
11 pass
12
13
14 class ContextDict(dict):
15 def __init__(self, context, *args, **kwargs):
16 super().__init__(*args, **kwargs)
17
18 context.dicts.append(self)
19 self.context = context
20
21 def __enter__(self):
22 return self
23
24 def __exit__(self, *args, **kwargs):
25 self.context.pop()
26
27
28 class BaseContext:
29 def __init__(self, dict_=None):
30 self._reset_dicts(dict_)
31
32 def _reset_dicts(self, value=None):
33 builtins = {"True": True, "False": False, "None": None}
34 self.dicts = [builtins]
35 if isinstance(value, BaseContext):
36 self.dicts += value.dicts[1:]
37 elif value is not None:
38 self.dicts.append(value)
39
40 def __copy__(self):
41 duplicate = BaseContext()
42 duplicate.__class__ = self.__class__
43 duplicate.__dict__ = copy(self.__dict__)
44 duplicate.dicts = self.dicts[:]
45 return duplicate
46
47 def __repr__(self):
48 return repr(self.dicts)
49
50 def __iter__(self):
51 return reversed(self.dicts)
52
53 def push(self, *args, **kwargs):
54 dicts = []
55 for d in args:
56 if isinstance(d, BaseContext):
57 dicts += d.dicts[1:]
58 else:
59 dicts.append(d)
60 return ContextDict(self, *dicts, **kwargs)
61
62 def pop(self):
63 if len(self.dicts) == 1:
64 raise ContextPopException
65 return self.dicts.pop()
66
67 def __setitem__(self, key, value):
68 "Set a variable in the current context"
69 self.dicts[-1][key] = value
70
71 def set_upward(self, key, value):
72 """
73 Set a variable in one of the higher contexts if it exists there,
74 otherwise in the current context.
75 """
76 context = self.dicts[-1]
77 for d in reversed(self.dicts):
78 if key in d:
79 context = d
80 break
81 context[key] = value
82
83 def __getitem__(self, key):
84 "Get a variable's value, starting at the current context and going upward"
85 for d in reversed(self.dicts):
86 if key in d:
87 return d[key]
88 raise KeyError(key)
89
90 def __delitem__(self, key):
91 "Delete a variable from the current context"
92 del self.dicts[-1][key]
93
94 def __contains__(self, key):
95 return any(key in d for d in self.dicts)
96
97 def get(self, key, otherwise=None):
98 for d in reversed(self.dicts):
99 if key in d:
100 return d[key]
101 return otherwise
102
103 def setdefault(self, key, default=None):
104 try:
105 return self[key]
106 except KeyError:
107 self[key] = default
108 return default
109
110 def new(self, values=None):
111 """
112 Return a new context with the same properties, but with only the
113 values given in 'values' stored.
114 """
115 new_context = copy(self)
116 new_context._reset_dicts(values)
117 return new_context
118
119 def flatten(self):
120 """
121 Return self.dicts as one dictionary.
122 """
123 flat = {}
124 for d in self.dicts:
125 flat.update(d)
126 return flat
127
128 def __eq__(self, other):
129 """
130 Compare two contexts by comparing theirs 'dicts' attributes.
131 """
132 if not isinstance(other, BaseContext):
133 return NotImplemented
134 # flatten dictionaries because they can be put in a different order.
135 return self.flatten() == other.flatten()
136
137
138 class Context(BaseContext):
139 "A stack container for variable context"
140
141 def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None):
142 self.autoescape = autoescape
143 self.use_l10n = use_l10n
144 self.use_tz = use_tz
145 self.template_name = "unknown"
146 self.render_context = RenderContext()
147 # Set to the original template -- as opposed to extended or included
148 # templates -- during rendering, see bind_template.
149 self.template = None
150 super().__init__(dict_)
151
152 @contextmanager
153 def bind_template(self, template):
154 if self.template is not None:
155 raise RuntimeError("Context is already bound to a template")
156 self.template = template
157 try:
158 yield
159 finally:
160 self.template = None
161
162 def __copy__(self):
163 duplicate = super().__copy__()
164 duplicate.render_context = copy(self.render_context)
165 return duplicate
166
167 def update(self, other_dict):
168 "Push other_dict to the stack of dictionaries in the Context"
169 if not hasattr(other_dict, "__getitem__"):
170 raise TypeError("other_dict must be a mapping (dictionary-like) object.")
171 if isinstance(other_dict, BaseContext):
172 other_dict = other_dict.dicts[1:].pop()
173 return ContextDict(self, other_dict)
174
175
176 class RenderContext(BaseContext):
177 """
178 A stack container for storing Template state.
179
180 RenderContext simplifies the implementation of template Nodes by providing a
181 safe place to store state between invocations of a node's `render` method.
182
183 The RenderContext also provides scoping rules that are more sensible for
184 'template local' variables. The render context stack is pushed before each
185 template is rendered, creating a fresh scope with nothing in it. Name
186 resolution fails if a variable is not found at the top of the RequestContext
187 stack. Thus, variables are local to a specific template and don't affect the
188 rendering of other templates as they would if they were stored in the normal
189 template context.
190 """
191
192 template = None
193
194 def __iter__(self):
195 yield from self.dicts[-1]
196
197 def __contains__(self, key):
198 return key in self.dicts[-1]
199
200 def get(self, key, otherwise=None):
201 return self.dicts[-1].get(key, otherwise)
202
203 def __getitem__(self, key):
204 return self.dicts[-1][key]
205
206 @contextmanager
207 def push_state(self, template, isolated_context=True):
208 initial = self.template
209 self.template = template
210 if isolated_context:
211 self.push()
212 try:
213 yield
214 finally:
215 self.template = initial
216 if isolated_context:
217 self.pop()
218
219
220 class RequestContext(Context):
221 """
222 This subclass of template.Context automatically populates itself using
223 the processors defined in the engine's configuration.
224 Additional processors can be specified as a list of callables
225 using the "processors" keyword argument.
226 """
227
228 def __init__(
229 self,
230 request,
231 dict_=None,
232 processors=None,
233 use_l10n=None,
234 use_tz=None,
235 autoescape=True,
236 ):
237 super().__init__(dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape)
238 self.request = request
239 self._processors = () if processors is None else tuple(processors)
240 self._processors_index = len(self.dicts)
241
242 # placeholder for context processors output
243 self.update({})
244
245 # empty dict for any new modifications
246 # (so that context processors don't overwrite them)
247 self.update({})
248
249 @contextmanager
250 def bind_template(self, template):
251 if self.template is not None:
252 raise RuntimeError("Context is already bound to a template")
253
254 self.template = template
255 # Set context processors according to the template engine's settings.
256 processors = template.engine.template_context_processors + self._processors
257 updates = {}
258 for processor in processors:
259 context = processor(self.request)
260 try:
261 updates.update(context)
262 except TypeError as e:
263 raise TypeError(
264 f"Context processor {processor.__qualname__} didn't return a "
265 "dictionary."
266 ) from e
267
268 self.dicts[self._processors_index] = updates
269
270 try:
271 yield
272 finally:
273 self.template = None
274 # Unset context processors.
275 self.dicts[self._processors_index] = {}
276
277 def new(self, values=None):
278 new_context = super().new(values)
279 # This is for backwards-compatibility: RequestContexts created via
280 # Context.new don't include values from context processors.
281 if hasattr(new_context, "_processors_index"):
282 del new_context._processors_index
283 return new_context
284
285
286 def make_context(context, request=None, **kwargs):
287 """
288 Create a suitable Context from a plain dict and optionally an HttpRequest.
289 """
290 if context is not None and not isinstance(context, dict):
291 raise TypeError(
292 "context must be a dict rather than %s." % context.__class__.__name__
293 )
294 if request is None:
295 context = Context(context, **kwargs)
296 else:
297 # The following pattern is required to ensure values from
298 # context override those from template context processors.
299 original_context = context
300 context = RequestContext(request, **kwargs)
301 if original_context:
302 context.push(original_context)
303 return context