An HttpResponse that allows its data to be rendered into arbitrary media types.
| 12 | |
| 13 | |
| 14 | class Response(SimpleTemplateResponse): |
| 15 | """ |
| 16 | An HttpResponse that allows its data to be rendered into |
| 17 | arbitrary media types. |
| 18 | """ |
| 19 | |
| 20 | def __init__(self, data=None, status=None, |
| 21 | template_name=None, headers=None, |
| 22 | exception=False, content_type=None): |
| 23 | """ |
| 24 | Alters the init arguments slightly. |
| 25 | For example, drop 'template_name', and instead use 'data'. |
| 26 | |
| 27 | Setting 'renderer' and 'media_type' will typically be deferred, |
| 28 | For example being set automatically by the `APIView`. |
| 29 | """ |
| 30 | super().__init__(None, status=status) |
| 31 | |
| 32 | if isinstance(data, Serializer): |
| 33 | msg = ( |
| 34 | 'You passed a Serializer instance as data, but ' |
| 35 | 'probably meant to pass serialized `.data` or ' |
| 36 | '`.error`. representation.' |
| 37 | ) |
| 38 | raise AssertionError(msg) |
| 39 | |
| 40 | self.data = data |
| 41 | self.template_name = template_name |
| 42 | self.exception = exception |
| 43 | self.content_type = content_type |
| 44 | |
| 45 | if headers: |
| 46 | for name, value in headers.items(): |
| 47 | self[name] = value |
| 48 | |
| 49 | # Allow generic typing checking for responses. |
| 50 | def __class_getitem__(cls, *args, **kwargs): |
| 51 | return cls |
| 52 | |
| 53 | @property |
| 54 | def rendered_content(self): |
| 55 | renderer = getattr(self, 'accepted_renderer', None) |
| 56 | accepted_media_type = getattr(self, 'accepted_media_type', None) |
| 57 | context = getattr(self, 'renderer_context', None) |
| 58 | |
| 59 | assert renderer, ".accepted_renderer not set on Response" |
| 60 | assert accepted_media_type, ".accepted_media_type not set on Response" |
| 61 | assert context is not None, ".renderer_context not set on Response" |
| 62 | context['response'] = self |
| 63 | |
| 64 | media_type = renderer.media_type |
| 65 | charset = renderer.charset |
| 66 | content_type = self.content_type |
| 67 | |
| 68 | if content_type is None and charset is not None: |
| 69 | content_type = f"{media_type}; charset={charset}" |
| 70 | elif content_type is None: |
| 71 | content_type = media_type |
no outgoing calls