context.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. from copy import copy
  2. from django.utils.module_loading import import_string
  3. # Cache of actual callables.
  4. _standard_context_processors = None
  5. # We need the CSRF processor no matter what the user has in their settings,
  6. # because otherwise it is a security vulnerability, and we can't afford to leave
  7. # this to human error or failure to read migration instructions.
  8. _builtin_context_processors = ('django.core.context_processors.csrf',)
  9. class ContextPopException(Exception):
  10. "pop() has been called more times than push()"
  11. pass
  12. class ContextDict(dict):
  13. def __init__(self, context, *args, **kwargs):
  14. super(ContextDict, self).__init__(*args, **kwargs)
  15. context.dicts.append(self)
  16. self.context = context
  17. def __enter__(self):
  18. return self
  19. def __exit__(self, *args, **kwargs):
  20. self.context.pop()
  21. class BaseContext(object):
  22. def __init__(self, dict_=None):
  23. self._reset_dicts(dict_)
  24. def _reset_dicts(self, value=None):
  25. builtins = {'True': True, 'False': False, 'None': None}
  26. self.dicts = [builtins]
  27. if value is not None:
  28. self.dicts.append(value)
  29. def __copy__(self):
  30. duplicate = copy(super(BaseContext, self))
  31. duplicate.dicts = self.dicts[:]
  32. return duplicate
  33. def __repr__(self):
  34. return repr(self.dicts)
  35. def __iter__(self):
  36. for d in reversed(self.dicts):
  37. yield d
  38. def push(self, *args, **kwargs):
  39. return ContextDict(self, *args, **kwargs)
  40. def pop(self):
  41. if len(self.dicts) == 1:
  42. raise ContextPopException
  43. return self.dicts.pop()
  44. def __setitem__(self, key, value):
  45. "Set a variable in the current context"
  46. self.dicts[-1][key] = value
  47. def __getitem__(self, key):
  48. "Get a variable's value, starting at the current context and going upward"
  49. for d in reversed(self.dicts):
  50. if key in d:
  51. return d[key]
  52. raise KeyError(key)
  53. def __delitem__(self, key):
  54. "Delete a variable from the current context"
  55. del self.dicts[-1][key]
  56. def has_key(self, key):
  57. for d in self.dicts:
  58. if key in d:
  59. return True
  60. return False
  61. def __contains__(self, key):
  62. return self.has_key(key)
  63. def get(self, key, otherwise=None):
  64. for d in reversed(self.dicts):
  65. if key in d:
  66. return d[key]
  67. return otherwise
  68. def new(self, values=None):
  69. """
  70. Returns a new context with the same properties, but with only the
  71. values given in 'values' stored.
  72. """
  73. new_context = copy(self)
  74. new_context._reset_dicts(values)
  75. return new_context
  76. def flatten(self):
  77. """
  78. Returns self.dicts as one dictionary
  79. """
  80. flat = {}
  81. for d in self.dicts:
  82. flat.update(d)
  83. return flat
  84. def __eq__(self, other):
  85. """
  86. Compares two contexts by comparing theirs 'dicts' attributes.
  87. """
  88. if isinstance(other, BaseContext):
  89. # because dictionaries can be put in different order
  90. # we have to flatten them like in templates
  91. return self.flatten() == other.flatten()
  92. # if it's not comparable return false
  93. return False
  94. class Context(BaseContext):
  95. "A stack container for variable context"
  96. def __init__(self, dict_=None, autoescape=True, current_app=None,
  97. use_l10n=None, use_tz=None):
  98. self.autoescape = autoescape
  99. self.current_app = current_app
  100. self.use_l10n = use_l10n
  101. self.use_tz = use_tz
  102. self.render_context = RenderContext()
  103. super(Context, self).__init__(dict_)
  104. def __copy__(self):
  105. duplicate = super(Context, self).__copy__()
  106. duplicate.render_context = copy(self.render_context)
  107. return duplicate
  108. def update(self, other_dict):
  109. "Pushes other_dict to the stack of dictionaries in the Context"
  110. if not hasattr(other_dict, '__getitem__'):
  111. raise TypeError('other_dict must be a mapping (dictionary-like) object.')
  112. self.dicts.append(other_dict)
  113. return other_dict
  114. class RenderContext(BaseContext):
  115. """
  116. A stack container for storing Template state.
  117. RenderContext simplifies the implementation of template Nodes by providing a
  118. safe place to store state between invocations of a node's `render` method.
  119. The RenderContext also provides scoping rules that are more sensible for
  120. 'template local' variables. The render context stack is pushed before each
  121. template is rendered, creating a fresh scope with nothing in it. Name
  122. resolution fails if a variable is not found at the top of the RequestContext
  123. stack. Thus, variables are local to a specific template and don't affect the
  124. rendering of other templates as they would if they were stored in the normal
  125. template context.
  126. """
  127. def __iter__(self):
  128. for d in self.dicts[-1]:
  129. yield d
  130. def has_key(self, key):
  131. return key in self.dicts[-1]
  132. def get(self, key, otherwise=None):
  133. return self.dicts[-1].get(key, otherwise)
  134. def __getitem__(self, key):
  135. return self.dicts[-1][key]
  136. # This is a function rather than module-level procedural code because we only
  137. # want it to execute if somebody uses RequestContext.
  138. def get_standard_processors():
  139. from django.conf import settings
  140. global _standard_context_processors
  141. if _standard_context_processors is None:
  142. processors = []
  143. collect = []
  144. collect.extend(_builtin_context_processors)
  145. collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS)
  146. for path in collect:
  147. func = import_string(path)
  148. processors.append(func)
  149. _standard_context_processors = tuple(processors)
  150. return _standard_context_processors
  151. class RequestContext(Context):
  152. """
  153. This subclass of template.Context automatically populates itself using
  154. the processors defined in TEMPLATE_CONTEXT_PROCESSORS.
  155. Additional processors can be specified as a list of callables
  156. using the "processors" keyword argument.
  157. """
  158. def __init__(self, request, dict_=None, processors=None, current_app=None,
  159. use_l10n=None, use_tz=None):
  160. Context.__init__(self, dict_, current_app=current_app,
  161. use_l10n=use_l10n, use_tz=use_tz)
  162. if processors is None:
  163. processors = ()
  164. else:
  165. processors = tuple(processors)
  166. updates = dict()
  167. for processor in get_standard_processors() + processors:
  168. updates.update(processor(request))
  169. self.update(updates)