python - flask : `@after_this_request` 不工作

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

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

为此我找到了这个 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

最佳答案

只需从 flask 导入 after_this_request,无需修改 after_request 或创建 hook。

from flask import after_this_request

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

关于python - flask : `@after_this_request` 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38993146/

相关文章:

python - 如何强制 matplotlib 在 Y 轴上只显示整数

python - 这是否正常工作 - Python 3 中的斐波那契总和

python-3.x - 执行 select pg_notify 的 Python psycopg2 不起作用

python - 导入时模拟模块全局变量

python - 使用 Apache mod_wsgi 进行 HTTP 流传输

python - 将 json 数据传递给模板

python - Django 装置错误 : Unknown application

python - Flask中如何打印出客户端请求到URL的所有数据?

python - Python如何查找模块和方法

Python 连接不显示 Swagger UI