我已经搜索了一段时间,试图弄清楚如何监视文件夹的更改,然后使用 FastAPI 触发。
基本上,当文件添加到文件夹时,快速 API 上的事件将文件名和文件路径保存在数据库中。
我发现有一个名为 watchdog 的包,但它如何与快速 API 集成。是我还找不到的。
from fastapi import FastAPI
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
app = FastAPI()
class MyHandler(FileSystemEventHandler):
def __init__(self, target_folder_path):
super().__init__()
self.target_folder_path = target_folder_path
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)
def start_watchdog_thread():
watchdog_thread.start()
def stop_watchdog_thread():
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