Liutprand
Liutprand

Reputation: 557

decorator @after_this_request not working

i'm learning Flask so forgive me if the question seems trivial. I'm building a very simple app generating a wordcloud (in a .png image) from the text inserted in a form. The problem is that I want to delete the image after giving it to the user.

I tried to use the @after_this_request decorator but it seems is not working (not even the print function you can see in the code below).

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 ()

I would expect the images to be deleted. I'm running this on MacOSX, if that can help...

Any advice? Thanks in advance!

Upvotes: 1

Views: 951

Answers (1)

Fine
Fine

Reputation: 2154

Python is a dynamic language, so everything is evaluated in a runtime. For the @after_this_request block to be evaluated, python interpreter first needs to reach those lines of code. But, with the return render_template ..., evaluation of the result function finishes and code-block of the @after_this_request is never reached and not evaluated, like it's never existed. Try moving this block to the beginning of the result function.

Upvotes: 1

Related Questions