我有一个Flask (实际上不是Flask,它是Quart,一个具有相同语法和功能的异步版本的Flask )应用程序,它提供由命令行工具临时创建的静态文件。我想在文件送达后将其删除。我可以使用普通的路由(不是静态的)来做到这一点,比如(伪代码,未测试):
@after_this_request
def delete_file():
path = "C:\Windows\System32\explorer.exe"
os.remove(path)我的问题是,如何使用静态文件实现相同的功能?
发布于 2021-05-02 02:00:30
通过创建一个蓝图并让它完成静态文件的所有提升,解决了这个问题。我将建议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')https://stackoverflow.com/questions/67340382
复制相似问题