我想使用DRF发送图像以响应某个网址,为此我写了这些代码:
#Renderer class
class ImageRenderer(renderers.BaseRenderer):
media_type = 'image/png'
format = 'image'
def render(self, data, media_type=None, renderer_context=None):
return data
#view class
class ShowImage(APIView):
renderer_classes = (ImageRenderer,)
def get(self, request, format=None):
print ('format', format)
if format == 'image':
image_file = open('path_to_image', 'rb')
response = HttpResponse(image_file, content_type='image/png')
response['Content-Disposition'] = 'attachment; filename={}'.format('image_filename')
#urls.py
urlpatterns = format_suffix_patterns([
url(r'image/?$', views.ShowImage.as_view())
])
但我的问题是输入format
总是None
,尽管request.accepted_media_type
向我显示image/png
我使用httpie
尝试了这些请求:
http -vj 127.0.0.1:8000/api/image Accept:image/png
http -vj 127.0.0.1:8000/api/image.image Accept:image/png
但我无法得到我期望的格式。使用DRF时我的错误是什么?