python - 如何使用 Django REST Framework 返回生成的文件下载?

标签 python django ms-word django-rest-framework download

我需要将生成的文件下载作为 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/

相关文章:

python - RPI dht22 带 flask : Unable to set line 4 to input - Timed out waiting for PulseIn message

python - Pygame 窗口在 Mac 上无法关闭的问题

python - 自定义 Django 管理面板?

ms-word - 如何在 Word 2010 中将所有标题部分合并/组合为仅一个标题部分

javascript - 标题中的图像在 Word for Desktop 中显示,但在 Word Online 中消失

python - 将Windows中vba宏调用的python脚本结果返回给Word vba

python - 使用不规则张量和 while 循环时,XLA 无法推导出跨步切片的编译时间常数输出形状

Python __str__ - 它可以有歧义吗?

python - Django 检索模型的所有相关属性

python - 现场生产中 argon2 hasher 的 Django 问题