【发布时间】:2017-11-23 09:34:38
【问题描述】:
我正在编写一个脚本来下载一个 zip 文件。我读了很多关于如何做到这一点的文章,但我仍然遇到了一些麻烦。正如你在代码中看到的,我首先创建了一个临时文件,在上面写入数据,然后压缩并下载。问题是结果:一个 zip 存档,里面有一个空文件。这是代码:
f = tempfile.NamedTemporaryFile()
f.write(html.encode('utf-8'))
print(f.read) #the "writing of tmp file" seem to work, the expected output is right
fzip = ZipFile("test.zip","w")
fzip.write(f.name,'exercise.html') #this file remains empty
response = HttpResponse(fzip, content_type="application/zip")
response['Content-Disposition'] = 'attachment; "filename=test.zip"'
return response
我已经尝试设置 NamedTemporaryFile(delete=False) 或 seek(0) 之类的东西。我认为问题出在 fzip.write 上,但实际上我想不出其他解决方案,有人可以帮忙吗? 谢谢:)
【问题讨论】:
标签: python django download django-rest-framework zip