【发布时间】:2016-12-23 21:44:12
【问题描述】:
我想在用户下载烧瓶应用程序创建的文件后删除文件。
为此,我发现这个answer on SO 没有按预期工作并引发错误,告诉您after_this_request 未定义。
因此,我对Flask's documentation providing a sample snippet 进行了更深入的了解,了解如何使用该方法。因此,我通过定义 after_this_request 函数来扩展我的代码,如示例 sn-p 所示。
分别执行代码。运行服务器按预期工作。但是,该文件没有被删除,因为@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
【问题讨论】:
标签: python python-3.x flask request delete-file