提供要下载的 .json 文件

Ev.*_*Ev. 4 python django

我正在尝试通过此函数提供 .json 文件。问题是每次我发出请求时,浏览器都会显示内容而不是下载文件。

我认为这可能是因为我将其.read()用作 HttpResponse 对象构造函数的参数。但是,如果我只使用文件对象,则会出现以下异常:

TypeError: cannot serialize '_io.BufferedRandom' object
Run Code Online (Sandbox Code Playgroud)

代码

try:
    invoices = models.Invoice.objects.filter(pk__in=document_ids).order_by(*ordering)
    pcustomers = models.CustomerProxy.objects.all()
    mixed_query = list(invoices) + list(pcustomers)

    file = tempfile.NamedTemporaryFile(suffix='.json')
    file.write(serializers.serialize('json', mixed_query).encode())
    file.seek(0)

    response = HttpResponse(file.read(), content_type='application/json')
    response['Content-Disposition'] = 'attachment; filename=%s' % file.name
    response['Content-Length'] = os.path.getsize(file.name)

except Exception:
    raise

return response
Run Code Online (Sandbox Code Playgroud)

rap*_*phv 8

您不需要经历整个文件生成过程来创建可下载文件,您只需要正常添加 Content-Disposition 标头即可。下面的代码有效吗?

...
mixed_query = list(invoices) + list(pcustomers)
json_str = serializers.serialize('json', mixed_query))
response = HttpResponse(json_str, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename=export.json'
Run Code Online (Sandbox Code Playgroud)