我需要将生成的文件下载作为 Django REST Framework 响应返回。我尝试了以下方法:
def retrieve(self, request, *args, **kwargs):
template = webodt.ODFTemplate('test.odt')
queryset = Pupils.objects.get(id=kwargs['pk'])
serializer = StudentSerializer(queryset)
context = dict(serializer.data)
document = template.render(Context(context))
doc = converter().convert(document, format='doc')
res = HttpResponse(
FileWrapper(doc),
content_type='application/msword'
)
res['Content-Disposition'] = u'attachment; filename="%s_%s.zip"' % (context[u'surname'], context[u'name'])
return res
但它返回一个 msword 文档作为 json
。
如何让它开始以文件形式下载?
最佳答案
这是一个直接从 DRF 返回文件下载的示例。诀窍是使用自定义渲染器,这样您就可以直接从 View 返回响应:
from django.http import FileResponse
from rest_framework import viewsets, renderers
from rest_framework.decorators import action
class PassthroughRenderer(renderers.BaseRenderer):
"""
Return data as-is. View should supply a Response.
"""
media_type = ''
format = ''
def render(self, data, accepted_media_type=None, renderer_context=None):
return data
class ExampleViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Example.objects.all()
@action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,))
def download(self, *args, **kwargs):
instance = self.get_object()
# get an open file handle (I'm just using a file attached to the model for this example):
file_handle = instance.file.open()
# send file
response = FileResponse(file_handle, content_type='whatever')
response['Content-Length'] = instance.file.size
response['Content-Disposition'] = 'attachment; filename="%s"' % instance.file.name
return response
请注意,我使用的是自定义端点 download
而不是默认端点 retrieve
,因为这样可以轻松覆盖此端点而不是整个 View 集——无论如何,列表和详细信息返回常规 JSON 往往是有意义的。如果您想有选择地返回文件下载,您可以向自定义渲染器添加更多逻辑。
关于python - 如何使用 Django REST Framework 返回生成的文件下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697529/