How can I run a function after each request to a static resource in Flask?

486 Views Asked by At

I have a Flask (It's not actually Flask, it's Quart, an asynchronous version of Flask with the same syntax and features) application that serves static files that are created temporarily by a command line tool. I want to delete the files after they have been served. I can do this with a normal route (not static) like so (pseudo-code, not tested):

@after_this_request
def delete_file():
  path = "C:\Windows\System32\explorer.exe"
  os.remove(path)

My question is, how do I achieve the same thing with a static file?

1

There are 1 best solutions below

0
On BEST ANSWER

Solved it by creating a blueprint and letting it do all the lifting for static files. I'll make a suggestion to Flask and Quart to add an official version of this feature. If you're using Flask, not Quart, then change all the async defs to def

static_bp.py:

from quart import Blueprint, request
import threading
import time
import os

static = Blueprint('static', __name__, static_url_path="/", static_folder="static")

@static.after_request
async def after_request_func(response):
    if response.status_code == 200:
        file_path = request.base_url.replace("http://ip:port/", "")
        t = threading.Thread(target=delete_after_request_thread, args=[file_path])
        t.setDaemon(False)
        t.start()
    return response

def delete_after_request_thread(file_path):
    time.sleep(2000)
    os.remove(file_path)

main.py (Replace Quart with Flask if you are running Flask):

app = Quart(__name__, "/static", static_folder=None)
app.register_blueprint(static, url_prefix='/static')