2016-08-17 77 views
1

我想在用户下载由烧瓶应用程序创建的文件后删除文件。烧瓶:`@ 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

回答

1

后,仍然在瓶这一请求功能没有具体。在之后只有,每请求挂钩,这是片段合作处理每个请求回叫的内容。

你没有实行挂钩:

@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打电话。 decorator在那里注册一个函数。没有上面的钩子,你的after_this_request修饰器本质上是无用的。

0

只需从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