You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. from django.http import HttpResponse
  2. from .loader import get_template, select_template
  3. class ContentNotRenderedError(Exception):
  4. pass
  5. class SimpleTemplateResponse(HttpResponse):
  6. rendering_attrs = ['template_name', 'context_data', '_post_render_callbacks']
  7. def __init__(self, template, context=None, content_type=None, status=None,
  8. charset=None, using=None):
  9. # It would seem obvious to call these next two members 'template' and
  10. # 'context', but those names are reserved as part of the test Client
  11. # API. To avoid the name collision, we use different names.
  12. self.template_name = template
  13. self.context_data = context
  14. self.using = using
  15. self._post_render_callbacks = []
  16. # _request stores the current request object in subclasses that know
  17. # about requests, like TemplateResponse. It's defined in the base class
  18. # to minimize code duplication.
  19. # It's called self._request because self.request gets overwritten by
  20. # django.test.client.Client. Unlike template_name and context_data,
  21. # _request should not be considered part of the public API.
  22. self._request = None
  23. # content argument doesn't make sense here because it will be replaced
  24. # with rendered template so we always pass empty string in order to
  25. # prevent errors and provide shorter signature.
  26. super().__init__('', content_type, status, charset=charset)
  27. # _is_rendered tracks whether the template and context has been baked
  28. # into a final response.
  29. # Super __init__ doesn't know any better than to set self.content to
  30. # the empty string we just gave it, which wrongly sets _is_rendered
  31. # True, so we initialize it to False after the call to super __init__.
  32. self._is_rendered = False
  33. def __getstate__(self):
  34. """
  35. Raise an exception if trying to pickle an unrendered response. Pickle
  36. only rendered data, not the data used to construct the response.
  37. """
  38. obj_dict = self.__dict__.copy()
  39. if not self._is_rendered:
  40. raise ContentNotRenderedError('The response content must be '
  41. 'rendered before it can be pickled.')
  42. for attr in self.rendering_attrs:
  43. if attr in obj_dict:
  44. del obj_dict[attr]
  45. return obj_dict
  46. def resolve_template(self, template):
  47. """Accept a template object, path-to-template, or list of paths."""
  48. if isinstance(template, (list, tuple)):
  49. return select_template(template, using=self.using)
  50. elif isinstance(template, str):
  51. return get_template(template, using=self.using)
  52. else:
  53. return template
  54. def resolve_context(self, context):
  55. return context
  56. @property
  57. def rendered_content(self):
  58. """Return the freshly rendered content for the template and context
  59. described by the TemplateResponse.
  60. This *does not* set the final content of the response. To set the
  61. response content, you must either call render(), or set the
  62. content explicitly using the value of this property.
  63. """
  64. template = self.resolve_template(self.template_name)
  65. context = self.resolve_context(self.context_data)
  66. content = template.render(context, self._request)
  67. return content
  68. def add_post_render_callback(self, callback):
  69. """Add a new post-rendering callback.
  70. If the response has already been rendered,
  71. invoke the callback immediately.
  72. """
  73. if self._is_rendered:
  74. callback(self)
  75. else:
  76. self._post_render_callbacks.append(callback)
  77. def render(self):
  78. """Render (thereby finalizing) the content of the response.
  79. If the content has already been rendered, this is a no-op.
  80. Return the baked response instance.
  81. """
  82. retval = self
  83. if not self._is_rendered:
  84. self.content = self.rendered_content
  85. for post_callback in self._post_render_callbacks:
  86. newretval = post_callback(retval)
  87. if newretval is not None:
  88. retval = newretval
  89. return retval
  90. @property
  91. def is_rendered(self):
  92. return self._is_rendered
  93. def __iter__(self):
  94. if not self._is_rendered:
  95. raise ContentNotRenderedError(
  96. 'The response content must be rendered before it can be iterated over.'
  97. )
  98. return super().__iter__()
  99. @property
  100. def content(self):
  101. if not self._is_rendered:
  102. raise ContentNotRenderedError(
  103. 'The response content must be rendered before it can be accessed.'
  104. )
  105. return super().content
  106. @content.setter
  107. def content(self, value):
  108. """Set the content for the response."""
  109. HttpResponse.content.fset(self, value)
  110. self._is_rendered = True
  111. class TemplateResponse(SimpleTemplateResponse):
  112. rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_request']
  113. def __init__(self, request, template, context=None, content_type=None,
  114. status=None, charset=None, using=None):
  115. super().__init__(template, context, content_type, status, charset, using)
  116. self._request = request