【发布时间】:2015-09-24 12:10:52
【问题描述】:
我目前正在使用 Python 上的 Pyramid 并在 Ubuntu 14.04 上运行的 Web 应用程序的导出功能。它将文件压缩到 NamedTemporaryFile 并通过 FileResponse 发回:
# Create the temporary file to store the zip
with NamedTemporaryFile(delete=True) as output:
map_zip = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)
length_mapdir = len(map_directory)
for root, dirs, files in os.walk(map_directory, followlinks=True):
for file in files:
file_path = os.path.join(root, file)
map_zip.write(file_path, file_path[length_mapdir:])
map_zip.close()
#Send the response as an attachement to let the user download the file
response = FileResponse(os.path.abspath(output.name))
response.headers['Content-Type'] = 'application/download'
response.headers['Content-Disposition'] = 'attachement; filename="'+filename+'"'
return response
在客户端,导出需要一些时间,然后出现文件下载弹出窗口,没有任何问题,一切都按计划在 zip 中。
压缩文件时,我可以看到 /tmp/ 中的文件越来越大,在出现下载弹出窗口之前,文件消失了。我假设这是 NamedTemporaryFile。
在压缩或下载文件时,使用的 RAM 量没有任何显着变化,它保持在 40mb 左右,而实际 zip 超过 800mb。
金字塔从哪里下载文件?根据我对 tempfile 的了解,它在关闭时是未链接的。如果这是真的,是否有可能另一个进程可能会在存储文件的内存上写入数据,从而破坏正在下载的任何金字塔?
【问题讨论】:
-
stackoverflow.com/questions/12949077/… 可能重复? FileIter 有一个被你的 WSGI 服务器调用的 close 方法 -- github.com/Pylons/pyramid/blob/master/pyramid/response.py#L111 ... 另见 blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html -- NamedTemporaryFile 上的 close() 将允许它在 GC 中被删除。