我需要创建一个临时文件来发送它,我试过:
# Create a temporary file --> I think it is ok (file not seen)
temporaryfile = NamedTemporaryFile(delete=False, dir=COMPRESSED_ROOT)
# The path to archive --> It's ok
root_dir = "something"
# Create a compressed file --> It bugs
data = open(f.write(make_archive(f.name, 'zip', root_dir))).read()
# Send the file --> Its ok
response = HttpResponse(data, mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s"' % unicode(downloadedassignment.name + '.zip')
return response
Run Code Online (Sandbox Code Playgroud)
我根本不知道这是不是很好的方法..
Chr*_*att 24
我实际上只需要做类似的事情,如果可能的话我想完全避免文件I/O. 这是我想出的:
import tempfile
import zipfile
with tempfile.SpooledTemporaryFile() as tmp:
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
archive.writestr('something.txt', 'Some Content Here')
# Reset file pointer
tmp.seek(0)
# Write file data to response
return HttpResponse(tmp.read(), mimetype='application/x-zip-compressed')
Run Code Online (Sandbox Code Playgroud)
它使用a SpooledTemporaryFile
,它将保留在内存中,除非它超出内存限制.然后,我将此临时文件设置为ZipFile
要使用的流.传递给writestr
的文件名只是文件在存档中的文件名,它与服务器的文件系统没有任何关系.然后,我只需要seek(0)
在ZipFile
完成它之后回滚文件指针()并将其转储到响应中.
Mar*_*ers 11
首先,您不需要创建一个NamedTemporaryFile
使用make_archive
; 您想要的只是make_archive
要创建的文件的唯一文件名.
.write
不返回文件名要关注该错误:您假设返回值f.write
是您可以打开的文件名; 只是寻找你的文件的开头,然后阅读:
f.write(make_archive(f.name, 'zip', root_dir))
f.seek(0)
data = f.read()
Run Code Online (Sandbox Code Playgroud)
请注意,您还需要清理您创建的临时文件(您设置delete=False
):
import os
f.close()
os.unlink(f.name)
Run Code Online (Sandbox Code Playgroud)
或者,只需省略delete
关键字以使其True
再次默认,然后仅关闭文件,无需取消链接.
您只是将新的存档名称写入临时文件.你最好直接阅读档案:
data = open(make_archive(f.name, 'zip', root_dir), 'rb').read()
Run Code Online (Sandbox Code Playgroud)
请注意,现在根本没有写入临时文件.
NamedTemporaryFile
完全避免创建:tempfile.mkdtemp()
改为使用生成一个临时目录来放置存档,然后清理它:
tmpdir = tempfile.mkdtemp()
try:
tmparchive = os.path.join(tmpdir, 'archive')
root_dir = "something"
data = open(make_archive(tmparchive, 'zip', root_dir), 'rb').read()
finally:
shutil.rmtree(tmpdir)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9213 次 |
最近记录: |