提供.json文件以供下载 [英] Serving .json file to download

查看:110
本文介绍了提供.json文件以供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to serve a .json file through this function. The problem is that every time I make the request the browser displays the content instead of downloading the file.

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

I think it could be due to the fact that I am using .read() as a parameter for the HttpResponse object constructor. However, if I use only the file object, I get the following exception:

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标头即可.下面的代码有效吗?

You don't need to go through the whole file generation process to create a downloadable file, you just need to add the Content-Disposition header normally. Does the code below work?

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

这篇关于提供.json文件以供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆