Reputation: 8613
I want to delete a file after the user downloaded a file which was created by the flask app.
For doing so I found this answer on SO which did not work as expected and raised an error telling that after_this_request
is not defined.
Due to that I had a deeper look into Flask's documentation providing a sample snippet about how to use that method. So, I extended my code by defining a after_this_request
function as shown in the sample snippet.
Executing the code resp. running the server works as expected. However, the file is not removed because @after_this_request
is not called which is obvious since After request ...
is not printed to Flask's output in the terminal:
#!/usr/bin/env python3
# coding: utf-8
import os
from operator import itemgetter
from flask import Flask, request, redirect, url_for, send_from_directory, g
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '.'
ALLOWED_EXTENSIONS = set(['csv', 'xlsx', 'xls'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def after_this_request(func):
if not hasattr(g, 'call_after_request'):
g.call_after_request = []
g.call_after_request.append(func)
return func
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
@after_this_request
def remove_file(response):
print('After request ...')
os.remove(filepath)
return response
return send_from_directory('.', filename=filepath, as_attachment=True)
return '''
<!doctype html>
<title>Upload a file</title>
<h1>Uplaod new file</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
What do I miss here? How can I ensure calling the function following to the @after_this_request
decorator in order to delete the file after it was downloaded by the user?
Note: Using Flask version 0.11.1
Upvotes: 6
Views: 11024
Reputation: 273
Just import after_this_request from flask, you don't need to modify after_request or create a hook.
from flask import after_this_request
@after_this_request
def remove_file(response):
print('After request ...')
os.remove(filepath)
return response
Upvotes: 7
Reputation: 1123400
Make sure to import the decorator from flask.after_this_request
. The decorator is new in Flask 0.9.
If you are using Flask 0.8 or older, then there is no specific after this request functionality. There is only a after every request hook, which is what the snippet coopts to handle per-request call-backs.
So unless you are using Flask 0.9 or newer you need to implement the documented hook yourself:
@app.after_request
def per_request_callbacks(response):
for func in getattr(g, 'call_after_request', ()):
response = func(response)
return response
So that hook is run after each and every request, and looks for a list of hooks to call in g.call_after_request
. The after_this_request
decorator registers a function there.
Upvotes: 6