我正在尝试通过此功能提供.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标头即可。下面的代码有效吗?
...
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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句