2012-09-20 16:06:27 +04:00
|
|
|
from django.core.handlers.wsgi import STATUS_CODE_TEXT
|
2012-09-20 20:44:34 +04:00
|
|
|
from django.template.response import SimpleTemplateResponse
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
|
|
|
class Response(SimpleTemplateResponse):
|
|
|
|
"""
|
|
|
|
An HttpResponse that allows it's data to be rendered into
|
|
|
|
arbitrary media types.
|
|
|
|
"""
|
|
|
|
|
2012-10-05 16:04:34 +04:00
|
|
|
def __init__(self, data=None, status=200,
|
2012-10-05 15:13:44 +04:00
|
|
|
template_name=None, headers=None):
|
2012-09-20 16:06:27 +04:00
|
|
|
"""
|
|
|
|
Alters the init arguments slightly.
|
|
|
|
For example, drop 'template_name', and instead use 'data'.
|
|
|
|
|
|
|
|
Setting 'renderer' and 'media_type' will typically be defered,
|
|
|
|
For example being set automatically by the `APIView`.
|
|
|
|
"""
|
|
|
|
super(Response, self).__init__(None, status=status)
|
|
|
|
self.data = data
|
|
|
|
self.headers = headers and headers[:] or []
|
2012-10-05 15:13:44 +04:00
|
|
|
self.template_name = template_name
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
@property
|
|
|
|
def rendered_content(self):
|
2012-10-05 13:23:47 +04:00
|
|
|
renderer = self.accepted_renderer
|
2012-10-05 15:13:44 +04:00
|
|
|
media_type = self.accepted_media_type
|
2012-10-05 13:23:47 +04:00
|
|
|
|
2012-10-05 15:13:44 +04:00
|
|
|
assert renderer, "No accepted renderer set on Response"
|
|
|
|
assert media_type, "No accepted media type set on Response"
|
2012-09-30 18:55:24 +04:00
|
|
|
|
2012-10-05 16:04:34 +04:00
|
|
|
self['Content-Type'] = media_type
|
2012-09-20 16:06:27 +04:00
|
|
|
if self.data is None:
|
2012-10-05 13:23:47 +04:00
|
|
|
return renderer.render()
|
|
|
|
|
2012-10-05 15:13:44 +04:00
|
|
|
return renderer.render(self.data, media_type)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
@property
|
|
|
|
def status_text(self):
|
|
|
|
"""
|
|
|
|
Returns reason text corresponding to our HTTP response status code.
|
|
|
|
Provided for convenience.
|
|
|
|
"""
|
|
|
|
return STATUS_CODE_TEXT.get(self.status_code, '')
|