module_watch_dog.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from watchdog.events import FileSystemEventHandler
  2. from watchdog.observers import Observer
  3. import settings
  4. import time
  5. import os
  6. from utils.utils_func import get_folder, check_path
  7. import datetime
  8. from utils.SingletonType import SingletonType
  9. from databases import CRUD,SqlQuery,PhotoRecord
  10. from databases import CRUD, SqlQuery, PhotoRecord
  11. def updateImageRaw(time_str, image_path, goods_art_no, image_index):
  12. session = SqlQuery()
  13. crud = CRUD(PhotoRecord)
  14. res = crud.read(
  15. session,
  16. conditions={
  17. "image_path": None,
  18. "goods_art_no": goods_art_no,
  19. "image_index": image_index,
  20. },
  21. )
  22. if res:
  23. # 格式化为年月日时分
  24. update = {
  25. "image_path": image_path,
  26. "photo_create_time": time_str,
  27. }
  28. crud.update(
  29. session,
  30. res.id,
  31. **update,
  32. )
  33. class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
  34. instance = None
  35. init_flag = None
  36. def __init__(self):
  37. # if self.init_flag:
  38. # return
  39. # else:
  40. # self.init_flag = True
  41. self.goods_art_no = None
  42. self.image_index = -1
  43. super().__init__()
  44. # self.window = window
  45. FileSystemEventHandler.__init__(self)
  46. self.receive_photo_data = []
  47. # 以下为测试用途
  48. self._get_image_index = -1
  49. self.observer = None
  50. self.last_create_time = datetime.datetime.now()
  51. def start_observer(self,path):
  52. if self.observer != None:
  53. return
  54. print("图片保存目录:", path)
  55. if path == None or path == "":
  56. return
  57. self.observer = Observer()
  58. watch_path = self.check_and_get_real_dir(path)
  59. if watch_path:
  60. self.observer.schedule(self, watch_path, recursive=True) # recursive 遍历目录
  61. self.observer.start()
  62. print("开启开门狗目录监听")
  63. else:
  64. print("路径错误不存在")
  65. def check_and_get_real_dir(self, watch_path):
  66. """
  67. 逻辑:
  68. 1、检查当前路径如包含Originals 则定位到对应Originals的父级目录
  69. 2、如没有Originals,则认定为一个普通目录(且子文件夹没有Originals),否则定位到父级目录
  70. """
  71. if not os.path.exists(watch_path):
  72. return None
  73. if "Originals" in watch_path:
  74. root_path = watch_path.split("Originals", 1)[0]
  75. else:
  76. if "Originals" in [x["folder_name"] for x in get_folder(watch_path)]:
  77. root_path = watch_path
  78. else:
  79. return watch_path
  80. # 检查并创建日期
  81. now = datetime.datetime.now()
  82. year = now.year
  83. month = now.month
  84. day = now.day
  85. path = r"{root_path}\Originals\{year}\{month}\{day}".format(root_path=root_path, year=year, month=month, day=day)
  86. check_path(path)
  87. print("watch_path:",path)
  88. return path
  89. def on_moved(self, event):
  90. # if event.is_directory:
  91. # print("directory moved from {0} to {1}".format(event.src_path, event.dest_path))
  92. # else:
  93. # print("file moved from {0} to {1}".format(event.src_path, event.dest_path))
  94. # if os.path.split(event.dest_path)[0] == settings.PhotoOutputDir:
  95. # print("1111111")
  96. pass
  97. def updatePhotoRecord(self):
  98. session = SqlQuery()
  99. crud = CRUD(PhotoRecord)
  100. crud.read()
  101. def on_created(self, event):
  102. if not event.is_directory:
  103. file_path = event.src_path
  104. print("file created:{0}".format(file_path))
  105. self.receive_photo_data.append(file_path)
  106. # self.get_photo_info(file_path)
  107. # self.window.data_sign.emit({"_type": "photo_number_music_play"})
  108. try:
  109. take_time = time.time()
  110. self.send_log("获取文件file_path:{}".format(file_path))
  111. create_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
  112. # print("获取文件create_time:{}".format(create_time))
  113. self.get_photo_info(raw_path=file_path, create_time=create_time, take_time=take_time)
  114. self.send_log("获取文件create_time:{}".format(create_time))
  115. if self.goods_art_no == None:
  116. print("货号不存在,监听不写入")
  117. return
  118. if file_path == None:
  119. print("file_path不存在,监听不写入")
  120. return
  121. updateImageRaw(create_time, file_path, self.goods_art_no,self.image_index)
  122. except BaseException as e:
  123. print("获取文件create_time失败", e)
  124. self.send_log("获取文件处理失败{}".format(e))
  125. def send_log(self, text):
  126. print(text)
  127. def get_photo_info(self, raw_path, create_time, take_time):
  128. # 看门狗监听到系统有图片生成后,自动进行图片对应
  129. f_path = os.path.split(raw_path)[0]
  130. print("raw_path:", raw_path)
  131. # take_time = time.time() # 创建图片时间,默认为拍照时间
  132. time.sleep(0.2) # 等待原始图片文件写入
  133. # 查找真实的图片路径名称
  134. f = False
  135. if f:
  136. if not os.path.exists(raw_path):
  137. print("不存在", raw_path)
  138. for file in os.listdir(f_path):
  139. file_path = os.path.join(f_path, file)
  140. # 判断是否为文件
  141. if os.path.isfile(file_path):
  142. # 获取文件创建时间
  143. create_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
  144. # 更新最早时间
  145. if create_time > self.last_create_time:
  146. self.last_create_time = create_time
  147. raw_path = file_path
  148. # last_file_size = os.path.getsize(raw_path)
  149. # k = 30
  150. # # 检查文件是否有写入完成
  151. # flag = False
  152. # while k:
  153. # k -= 1
  154. # if k == 0:
  155. # break
  156. # _file_size = os.path.getsize(raw_path)
  157. # if last_file_size == _file_size:
  158. # flag = True
  159. # break
  160. # else:
  161. # last_file_size = _file_size
  162. # time.sleep(0.1)
  163. # if not flag:
  164. # return
  165. # 调用父程序,执行报错图片命令
  166. # self.window.show_img_on_photo_todo_list_sign(raw_path=raw_path, take_time=take_time)
  167. def stop(self):
  168. # 结束监听
  169. if self.observer is not None:
  170. self.observer.stop()
  171. print("结束监听")
  172. del self.observer
  173. def __new__(cls, *args, **kwargs):
  174. """如果当前没有实例时,调用父类__new__方法,生成示例,有则返回保存的内存地址。"""
  175. if not cls.instance:
  176. cls.instance = super().__new__(cls)
  177. return cls.instance
  178. def __del__(self):
  179. self.stop()
  180. print("结束监听,进程关闭")