本地计算机与生产服务器上send_file和tempfile的不同行为

时间:2019-07-11 21:42:25

标签: python-3.x flask pythonanywhere contextmanager

我有一个小的Flask应用程序,该应用程序利用Python的TemporaryDirectory创建一个zip文件并将其返回给客户端。代码段如下所示:

import tempfile, os, shutil
def process():
    with tempfile.TemporaryDirectory(dir=os.getcwd()) as tmpdir:
        with tempfile.TemporaryDirectory(dir=tmpdir) as wrapper_dir:

            #some processing
            zipfile = shutil.make_archive("azipfile", "zip", wrapper_dir)

        return send_file(zipfile, mimetype="zip", attachment_filename="azipfile.zip", as_attachment=True)

它嵌套2个临时目录,对内部目录进行压缩,然后将压缩文件发送给用户。如果我在本地计算机上运行该应用程序,则该应用程序的行为将达到预期效果,并且不会留下任何目录或文件,因为上下文管理器和tempfile都应在提供zipfile后很好地清理自身。

但是,当我在PythonAnywhere上运行它时,它将引发此错误:

OSError: [Errno 39] Directory not empty: '/home/{user}/{app}/{tempdirectory}'

从逻辑上讲,该错误是有道理的,因为temp目录仍然包含zipfile,但是为什么在生产环境和本地环境中运行它的行为会有差异?

0 个答案:

没有答案
相关问题