[英]Django Rest return 0 bytes zip file in response
我有一个简单的方法来返回带有.pdf文件的zip存档。 这是生成zip归档文件并将其返回的代码的一部分:
pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf()
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
with archive:
archive.writestr('report.pdf', pdf_file)
wrapper = FileWrapper(temp)
http_response = HttpResponse(wrapper, content_type='application/zip')
http_response['Content-Disposition'] = 'attachment; filename=report.zip'
return http_response
问题是我得到0字节的zip存档响应。 我做错了什么?
更新
另外我在return
之前添加了这两行代码,但随着它我seek of closed file
http_response['Content_Length'] = temp.tell()
temp.seek(0)
感谢您对@Will Keeling的帮助
我通过在HttpResponse
之前添加temp.seek()
并删除http_response['Content_Length'] = temp.tell()
解决我的问题,因为关闭后无法使用temp。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.