context.py 9.3 KB

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