装饰器@after_this_request不起作用

时间:2019-02-12 16:56:47

标签: python flask

我正在学习Flask,所以如果这个问题看起来微不足道,请原谅我。我正在构建一个非常简单的应用程序,该应用程序从插入表单的文本生成wordcloud(.png图像)。 问题是我想在将图像提供给用户后删除它。

我尝试使用@after_this_request装饰器,但似乎无法正常工作(甚至您在下面的代码中也看不到打印功能)。

from flask import Flask, request, render_template, after_this_request
import wordcloud
import time
import os

app=Flask (__name__)

@app.after_request
def add_header (r):
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    return r

@app.route ("/")
def main ():
    return render_template ("main.html")

@app.route ("/result", methods=["GET","POST"])
def result ():

    ts=str(time.time())

    if request.method == "POST":
        wc=wordcloud.WordCloud (width=1920, height=1080).generate (request.form["text"])
        wc.to_file ("static/wc_"+ts+".png")
        return render_template ("result.html", ts=ts)

    @after_this_request
    def remove_file (response):
        print ("Test")
        os.remove ("static/wc_"+ts+".png")
        return response

app.run ()

我希望图像被删除。我正在MacOSX上运行它,如果可以的话...

有什么建议吗? 预先感谢!

1 个答案:

答案 0 :(得分:1)

Python是一种动态语言,因此所有内容都在运行时进行评估。对于要评估的@after_this_request块,python解释器首先需要到达这些代码行。但是,使用return render_template ...时,对result函数的评估完成了,并且从未达到@after_this_request的代码块并且没有对其进行评估,就像从未存在过一样。尝试将此块移至result函数的开头。

相关问题