Reputation: 86
I have a website with a Flask backend, and when a particular URL is hit, a file is sent to the user's browser to be downloaded. For server space management, I want the file to be deleted as soon as it's sent to the user to be downloaded, so I added a finally block to delete the file:
@app.route('/api/conversions/<filename>', methods=['GET'])
def send_file(filename):
mimetype_value = 'audio/mp4' if os.path.splitext(filename)[1] == '.m4a' else ''
try:
return send_from_directory('conversions', filename, mimetype=mimetype_value, as_attachment=True)
finally:
delete_file(os.path.join('conversions', filename))
The interesting thing is that from what I've read, the finally
block should be running before the return
statement, but if that's the case then how is my website working? The file is being sent to the user without any problems, which should be impossible if the finally
block runs first as I'm deleting the file in the finally
block.
Upvotes: 0
Views: 91
Reputation: 1845
The sequence of events in your code is equivalent to this:
return_value = send_from_directory(...
delete_file(...
return return_value
Upvotes: 1