在每次请求 Flask 中的静态资源后,如何 运行 一个函数?

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

我有一个 Flask(它实际上不是 Flask,它是 Quart,Flask 的异步版本,具有相同的语法和功能)应用程序,它提供由命令行工具临时创建的静态文件。我想在文件送达后删除这些文件。我可以像这样使用普通路由(不是静态的)来做到这一点(伪代码,未测试):

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

我的问题是,如何使用静态文件实现相同的目的?

通过创建蓝图并让它完成静态文件的所有提升来解决它。我会向 Flask 和 Quart 建议添加此功能的正式版本。如果您使用的是 Flask 而不是 Quart,则将所有 async def 更改为 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(如果您是 运行 Flask,请将 Quart 替换为 Flask):

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