0
@app.route("/test")
def test_func():
    @after_this_request
    def delete_file(response):
        os.remove('test.txt')
        return response
        
    return send_file('test.txt')

I have test.txt in the same directory as my code. All I wanna do is delete the file I send, but when I access this GET method, I run into the following error:

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 -

thank you in advance

Patrick
  • 1,189
  • 5
  • 11
  • 19
  • You might consider using [celery](https://flask.palletsprojects.com/en/2.0.x/patterns/celery/). – jarmod Nov 12 '21 at 14:46

1 Answers1

2

The issue here is that @after_this_request causes delete_file() to be passed in the "proposed" response object produced by test_func(). @after_this_request gives delete_file() the opportunity to modify the response before it is sent.

So, your os.remove('test.txt') is actually being called before send_file() has completed.

You can see this in the help for @after_this_request. It says "The function is passed the response object and has to return the same or a new one." So you can see from that the code will be run before the response is actually returned.

For a solution, see this question.

Cargo23
  • 3,064
  • 16
  • 25