将文件添加到文件夹时,路径将保存为Db格式
我发现有一个软件包叫看门狗,但如何集成它与快速API。是什么,我还没有找到。
我已经修改了我的代码从原来的职位,所以监测将开始时,快速API启动位
from fastapi import FastAPI , Depends
from sqlalchemy.orm import Session
from session import get_session
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
app = FastAPI()
class MyHandler(FileSystemEventHandler):
db: Session
def __init__(self, target_folder_path, db: Session = Depends(get_session)):
super().__init__()
self.target_folder_path = target_folder_path
self.db = db
def on_created(self, event):
print(f"File {event.src_path} has been created in {self.target_folder_path}")
def on_modified(self, event):
print(f"File {event.src_path} has been modified in {self.target_folder_path}")
class WatchdogThread:
def __init__(self, target_folder_path):
self.observer = Observer()
self.target_folder_path = target_folder_path
def start(self):
event_handler = MyHandler(self.target_folder_path)
self.observer.schedule(event_handler, self.target_folder_path, recursive=True)
print(f"Starting the folder monitoring for {self.target_folder_path}")
self.observer.start()
def stop(self):
self.observer.stop()
print(f"Stopping the folder monitoring for {self.target_folder_path}")
self.observer.join()
target_folder_path = "/monitored"
watchdog_thread = WatchdogThread(target_folder_path)
# added this to start the monitoring.
@app.on_event("startup")
async def startup_event():
watchdog_thread.start()
@app.on_event("shutdown")
async def shutdown_event():
watchdog_thread.stop()
def main():
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, access_log=True, reload=True)
if __name__ == "__main__":
main()
#Docker-compose
volumes:
- ${TARGET_FOLDER_PARENT_PATH}:/monitored:rw
1条答案
按热度按时间polhcujo1#
它不是FastAPI部件,而是Uvicorn部件。您可以在此处查看源代码:https://github.com/encode/uvicorn/blob/master/uvicorn/supervisors/watchgodreload.pyhttps://github.com/encode/uvicorn/blob/master/uvicorn/supervisors/watchfilesreload.py