【问题标题】:Flask unable to delete file after send_file() [duplicate]send_file()后烧瓶无法删除文件[重复]
【发布时间】:2021-12-24 21:20:22
【问题描述】:
@app.route("/test")
def test_func():
    @after_this_request
    def delete_file(response):
        os.remove('test.txt')
        return response
        
    return send_file('test.txt')

我的 test.txt 与我的代码位于同一目录中。我想做的就是删除我发送的文件,但是当我访问这个 GET 方法时,我遇到了以下错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'test.txt' 127.0.0.1 - - [12/Nov/2021 19:47:53] "GET /test HTTP/1.1" 500 -

提前谢谢你

【问题讨论】:

  • 您可以考虑使用celery

标签: python api flask


【解决方案1】:

这里的问题是@after_this_request 导致delete_file()test_func() 生成的“建议”响应对象中传递。 @after_this_request 使 delete_file() 有机会在发送之前修改响应。

因此,您的 os.remove('test.txt') 实际上是在 send_file() 完成之前被调用的。

您可以在the help 中看到@after_this_request。它说“该函数传递了响应对象,并且必须返回相同的或新的。”所以你可以看到代码会在响应真正返回之前运行。

有关解决方案,请参阅this question

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2019-05-13
    • 2021-04-25
    • 2020-09-03
    • 2016-01-08
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2014-07-20
    相关资源
    最近更新 更多