Skip to main content
 首页 » 编程设计

python之服务 .json 文件下载

2025年05月04日16mengfanrong

我正在尝试通过此函数提供 .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'