An HttpResponse that allows its data to be rendered into arbitrary media types.
| 11 | |
| 12 | |
| 13 | class Response(SimpleTemplateResponse): |
| 14 | """ |
| 15 | An HttpResponse that allows its data to be rendered into |
| 16 | arbitrary media types. |
| 17 | """ |
| 18 | |
| 19 | def __init__(self, data=None, status=200, |
| 20 | template_name=None, headers=None, |
| 21 | exception=False, content_type=None): |
| 22 | """ |
| 23 | Alters the init arguments slightly. |
| 24 | For example, drop 'template_name', and instead use 'data'. |
| 25 | |
| 26 | Setting 'renderer' and 'media_type' will typically be deferred, |
| 27 | For example being set automatically by the `APIView`. |
| 28 | """ |
| 29 | super(Response, self).__init__(None, status=status) |
| 30 | self.data = data |
| 31 | self.template_name = template_name |
| 32 | self.exception = exception |
| 33 | self.content_type = content_type |
| 34 | |
| 35 | if headers: |
| 36 | for name, value in six.iteritems(headers): |
| 37 | self[name] = value |
| 38 | |
| 39 | @property |
| 40 | def rendered_content(self): |
| 41 | renderer = getattr(self, 'accepted_renderer', None) |
| 42 | media_type = getattr(self, 'accepted_media_type', None) |
| 43 | context = getattr(self, 'renderer_context', None) |
| 44 | |
| 45 | assert renderer, ".accepted_renderer not set on Response" |
| 46 | assert media_type, ".accepted_media_type not set on Response" |
| 47 | assert context, ".renderer_context not set on Response" |
| 48 | context['response'] = self |
| 49 | |
| 50 | charset = renderer.charset |
| 51 | content_type = self.content_type |
| 52 | |
| 53 | if content_type is None and charset is not None: |
| 54 | content_type = "{0}; charset={1}".format(media_type, charset) |
| 55 | elif content_type is None: |
| 56 | content_type = media_type |
| 57 | self['Content-Type'] = content_type |
| 58 | |
| 59 | ret = renderer.render(self.data, media_type, context) |
| 60 | if isinstance(ret, six.text_type): |
| 61 | assert charset, 'renderer returned unicode, and did not specify ' \ |
| 62 | 'a charset value.' |
| 63 | return bytes(ret.encode(charset)) |
| 64 | |
| 65 | if not ret: |
| 66 | del self['Content-Type'] |
| 67 | |
| 68 | return ret |
| 69 | |
| 70 | @property |