烧瓶:`@ after_this_request`不起作用 [英] flask: `@after_this_request` not working

查看:108
本文介绍了烧瓶:`@ after_this_request`不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to delete a file after the user downloaded a file which was created by the flask app.

为此,我找到了关于SO的答案未能按预期运行,并引发错误,提示未定义 after_this_request

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.

由于我对 Flask的文档提供了有关如何使用该方法的示例代码段。因此,我通过定义一个 after_this_request 函数来扩展代码,如示例代码所示。

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.

执行代码响应。运行服务器按预期工作。但是,不会删除该文件,因为没有调用 @after_this_request ,这很明显,因为没有请求 After ... 在终端上打印到Flask的输出:

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)

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

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?

注意:使用Flask版本0.11.1

推荐答案

请确保导入来自 flask.after_this_request 。装饰器是Flask 0.9中的新增功能。

Make sure to import the decorator from flask.after_this_request. The decorator is new in Flask 0.9.

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

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.

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

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

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

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.

这篇关于烧瓶:`@ after_this_request`不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆