gpt4 book ai didi

python - 服务 .json 文件下载

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:44 26 4
gpt4 key购买 nike

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

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

TypeError: cannot serialize '_io.BufferedRandom' object

代码

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

最佳答案

您无需经历整个文件生成过程即可创建可下载文件,您只需正常添加 Content-Disposition header 即可。下面的代码是否有效?

...
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'

关于python - 服务 .json 文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37298021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com