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
 
     
     
     
    