| 8 | |
| 9 | |
| 10 | class SimpleTemplateResponse(HttpResponse): |
| 11 | rendering_attrs = ["template_name", "context_data", "_post_render_callbacks"] |
| 12 | |
| 13 | def __init__( |
| 14 | self, |
| 15 | template, |
| 16 | context=None, |
| 17 | content_type=None, |
| 18 | status=None, |
| 19 | charset=None, |
| 20 | using=None, |
| 21 | headers=None, |
| 22 | ): |
| 23 | # It would seem obvious to call these next two members 'template' and |
| 24 | # 'context', but those names are reserved as part of the test Client |
| 25 | # API. To avoid the name collision, we use different names. |
| 26 | self.template_name = template |
| 27 | self.context_data = context |
| 28 | |
| 29 | self.using = using |
| 30 | |
| 31 | self._post_render_callbacks = [] |
| 32 | |
| 33 | # _request stores the current request object in subclasses that know |
| 34 | # about requests, like TemplateResponse. It's defined in the base class |
| 35 | # to minimize code duplication. |
| 36 | # It's called self._request because self.request gets overwritten by |
| 37 | # django.test.client.Client. Unlike template_name and context_data, |
| 38 | # _request should not be considered part of the public API. |
| 39 | self._request = None |
| 40 | |
| 41 | # content argument doesn't make sense here because it will be replaced |
| 42 | # with rendered template so we always pass empty string in order to |
| 43 | # prevent errors and provide shorter signature. |
| 44 | super().__init__("", content_type, status, charset=charset, headers=headers) |
| 45 | |
| 46 | # _is_rendered tracks whether the template and context has been baked |
| 47 | # into a final response. |
| 48 | # Super __init__ doesn't know any better than to set self.content to |
| 49 | # the empty string we just gave it, which wrongly sets _is_rendered |
| 50 | # True, so we initialize it to False after the call to super __init__. |
| 51 | self._is_rendered = False |
| 52 | |
| 53 | def __getstate__(self): |
| 54 | """ |
| 55 | Raise an exception if trying to pickle an unrendered response. Pickle |
| 56 | only rendered data, not the data used to construct the response. |
| 57 | """ |
| 58 | obj_dict = self.__dict__.copy() |
| 59 | if not self._is_rendered: |
| 60 | raise ContentNotRenderedError( |
| 61 | "The response content must be rendered before it can be pickled." |
| 62 | ) |
| 63 | for attr in self.rendering_attrs: |
| 64 | if attr in obj_dict: |
| 65 | del obj_dict[attr] |
| 66 | |
| 67 | return obj_dict |
no outgoing calls