问题描述
这是通过文件浏览器将文件添加到目录的事件问题。加载单个文件会产生一堆事件:
我想消息的数量取决于上传 zip 文件的时间。 我不知道如何用看门狗解决它,这是代码:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging
class Watcher:
DIRECTORY_TO_WATCH = "/input"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = DataHandler()
self.observer.schedule(event_handler,self.DIRECTORY_TO_WATCH,recursive=False)
self.observer.start()
try:
while True:
time.sleep(5000)
except:
self.observer.stop()
print("Error")
self.observer.join()
class DataHandler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == "created":
print(f"Received created event {event.src_path}")
elif event.event_type == "modified":
print(f"Received modified event {event.src_path}")
if __name__ == "__main__":
w = Watcher()
w.run()
解决方法
如果你只想为同一个文件打印一个事件,你可以保存最后修改的路径,只在新路径不同时打印消息:
@handler(...,method='POST')
def rtspserverendpoint(site_id: int,camera_id: int):
# find camera,which will allow us to check the correctness of the site_id as well
camera = db.session.query(Camera).get(camera_id)
if camera is None:
raise Exception(f"No camera with this {camera_id=}.")
if camera.site_id != site_id:
raise Exception(f"Camera with this {camera_id=} does not belong to the site with {site_id=}.")
new_obj = RtspServerEndpoint(
...,camera_id=camera_id,...,)
db.session.add(new_obj)
db.session.commit()
当然,您可以调整此代码以匹配您要应用于您的情况的确切逻辑,如果它被标记了 x 次,可能会再次打印它,或者跟踪自第一条消息以来的时间并再次打印它,如果距离上一条消息已经超过 x 秒/分钟。