我想在用户下载由烧瓶应用程序创建的文件后删除文件。烧瓶:`@ after_this_request`不起作用
为此,我找到了这个answer on SO,它没有按预期工作,并产生一个错误,告知after_this_request
没有定义。
由于我对Flask's documentation providing a sample snippet有更深入的了解如何使用该方法。所以,我通过定义after_this_request
函数扩展了我的代码,如示例代码片段所示。
执行代码或响应。运行服务器按预期工作。但是,不删除该文件,因为@after_this_request
不叫,因为After request ...
不打印到瓶的输出终端是显而易见的:
#!/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
后面的功能,以便在用户下载文件后删除文件?
注:使用瓶版本0.11.1