烧瓶:`@ after_this_request`无效

时间:2016-08-17 09:44:27

标签: python python-3.x flask request delete-file

我想在用户下载由烧瓶应用程序创建的文件后删除文件。

为此,我发现此answer on SO没有按预期工作,并引发错误,告知after_this_request未定义。

由于这一点,我对Flask's documentation providing a sample snippet有关如何使用该方法的深入研究。因此,我通过定义after_this_request函数来扩展我的代码,如示例代码段所示。

执行代码。运行服务器按预期工作。但是,该文件未被删除,因为未调用@after_this_request这是显而易见的,因为After request ...未打印到终端中Flask的输出中:

#!/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)

我在这里想念什么?如何确保调用@after_this_request装饰器后面的函数,以便在用户下载文件后删除该文件?

注意:使用Flask版本0.11.1

2 个答案:

答案 0 :(得分:2)

确保从flask.after_this_request导入装饰器。装饰器是Flask 0.9的新功能。

如果您使用的是Flask 0.8或更早版本,则此请求后没有特定的 功能。只有一个每个请求挂钩之后,这就是代码段处理每个请求回调的内容。

因此,除非您使用Flask 0.9或更新版本,否则您需要自己实现记录的钩子:

@app.after_request
def per_request_callbacks(response):
    for func in getattr(g, 'call_after_request', ()):
        response = func(response)
    return response

这样在每个请求之后运行钩子,并查找要在g.call_after_request中调用的钩子列表。 after_this_request装饰器在那里注册了一个函数。

答案 1 :(得分:1)

只需从flask中导入after_this_request,您就不需要修改after_request或创建一个钩子。

from flask import after_this_request

@after_this_request
def remove_file(response):
    print('After request ...')
    os.remove(filepath)
return response