Define a function after the request #Flask #memo #python

I love flask and django for making web app and often use Flask for web app development.

Sometime the app will serve files after getting user request. In this case, static files which are generated by the app will be stored in static folder. And the folder will store lots of files. So I would like to delete these files after serving the file to use. How to do it?

I searched google and found good solution ;) Flask has request callback function to do the task. ‘after_this_request‘ method is suitable for my situation.

An example of using the method is below. after_this_request is used as decorator.

from flask import Flask
from flask import render_template, after_this_request, request, send_file

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        # do something
        @after_this_request
        def rm_file(response):
            # remove generated file
            return response
         return send_file('generatedfile')
     return render_template('hoge.html')

Flask has many useful callback functions and I’ve never used them. So I would like to read the document and use them in my products.

Advertisement

Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: