我有一个Flask(它实际上不是Flask,而是Quart,一个具有相同语法和功能的异步版本的Flask(应用程序,它提供由命令行工具临时创建的静态文件。我想在文件送达后删除它们。我可以用一个正常的路由(不是静态的(这样做(伪代码,没有测试(:
@after_this_request
def delete_file():
path = "C:WindowsSystem32explorer.exe"
os.remove(path)
我的问题是,如何使用静态文件实现相同的功能?
通过创建蓝图并让它完成静态文件的所有提升来解决它。我会建议Flask和Quart添加此功能的官方版本。如果您使用的是烧瓶,而不是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(如果您正在运行烧瓶,请用烧瓶替换Quart(:
app = Quart(__name__, "/static", static_folder=None)
app.register_blueprint(static, url_prefix='/static')