Reputation: 5942
I'm building a Flask extension that needs to create a temporary folder when its init_app
-method is called. I'm planning to use Python's built-in tempfile.mkdtemp()
– however, I need to remove the temporary directory when the Flask app is stopped/torn down.
What is the correct way to do this?
I'm thinking there should be some sort of inverse of the init_app
-method.
Upvotes: 1
Views: 789
Reputation: 1123630
There is no teardown; generally Flask servers are expected to run 'forever'.
Leave it to the OS to delete the temporary directory or register an atexit
handler to clean up any such directories.
Note that it depends on your WSGI server forking model on how safe this is going to be. Some servers fork child processes after loading your Python module, so any globals are shared between these processes. If you created your temporary directory at the global level (not in a Flask before_first_request
hook) then you could end up with child processes that all share the same temporary directory, but each child being reaped triggering an atexit
handler. You may need to code defensively for this case.
Upvotes: 1