Browse Source

增加重试机制

rambo 1 month ago
parent
commit
ab05968db5
2 changed files with 48 additions and 39 deletions
  1. 17 16
      python/service/grenerate_main_image_test.py
  2. 31 23
      python/sockets/message_handler.py

+ 17 - 16
python/service/grenerate_main_image_test.py

@@ -472,10 +472,14 @@ class GeneratePic(object):
         )
         # ==========先进行剪切原图
         _s = time.time()
-        orign_im = Image.open(image_path)  # 原始图
+        with Image.open(image_path) as orign_im:
+            # 复制图像以便后续操作
+            orign_im = orign_im.copy()
         print("242  need_time_1:{}".format(time.time() - _s))
         orign_x, orign_y = orign_im.size
-        cut_image = Image.open(cut_image_path)  # 原始图的已扣图
+        with Image.open(cut_image_path) as cut_image:
+            # 复制图像以便后续操作
+            cut_image = cut_image.copy()
         cut_image, new_box = get_mini_crop_img(img=cut_image)
         im_shadow = orign_im.crop(new_box)  # 切图
         new_x, new_y = im_shadow.size
@@ -738,20 +742,17 @@ class GeneratePic(object):
                 )
                 # image_bg.save(out_path)
         # 在函数结束时使用更安全的关闭方式
-        try:
-            if 'orign_im' in locals() and orign_im:
-                orign_im.close()
-            if 'cut_image' in locals() and cut_image:
-                cut_image.close()
-            if 'logo_im' in locals() and logo_im:
-                logo_im.close()
-            if 'out_image_2' in locals() and out_image_2:
-                out_image_2.close()
-        except Exception as e:
-            logger.info(f"阴影处理关闭图片对象失败:{str(e)}")
-            print(f"Error closing images: {e}")
-        if output_queue is not None:
-            output_queue.put(True)
+        # 清理所有可能打开的图片对象
+        for img_var in ['orign_im', 'cut_image', 'logo_im', 'out_image_1', 'out_image_2']:
+            if img_var in locals():
+                img = locals()[img_var]
+                if hasattr(img, 'close'):
+                    try:
+                        img.close()
+                    except Exception as e:
+                        logger.warning(f"关闭图片对象 {img_var} 时出错: {e}")
+            if output_queue is not None:
+                output_queue.put(True)
         return True
     def get_scale(self,base_by_box, image_size):
         box_width, box_height = int(base_by_box[0]), int(base_by_box[1])

+ 31 - 23
python/sockets/message_handler.py

@@ -53,20 +53,25 @@ async def handlerCutOut(
         )
         await manager.send_personal_message(data, websocket)
 
-def handlerFolderDelete(limit_path,goods_art_no_arrays,is_write_txt_log):
+def handlerFolderDelete(limit_path, goods_art_no_arrays, is_write_txt_log):
     check_path(limit_path)
     move_folder_array = check_move_goods_art_no_folder(
-                "output", goods_art_no_arrays, limit_path
-            )
+        "output", goods_art_no_arrays, limit_path
+    )
+    
     for goods_art_revice in goods_art_no_arrays:
-                cutout_goods = f"{limit_path}/{goods_art_revice}"
-                if os.path.exists(cutout_goods):
-                    # 寻找当前被扣图的货号在现有目录中是否存在,如果存在先删除
-                    # 重新执行抠图操作
-                    try:
-                        shutil.rmtree(cutout_goods, onerror=settings.handle_remove_readonly)
-                        del move_folder_array[goods_art_revice]
-                    except PermissionError as e:
+        cutout_goods = f"{limit_path}/{goods_art_revice}"
+        if os.path.exists(cutout_goods):
+            # 尝试多次删除,增加成功率
+            retry_count = 3
+            while retry_count > 0:
+                try:
+                    shutil.rmtree(cutout_goods, onerror=settings.handle_remove_readonly)
+                    del move_folder_array[goods_art_revice]
+                    break
+                except PermissionError as e:
+                    retry_count -= 1
+                    if retry_count == 0:
                         logger.info(f"抠图前目录删除出现问题:{str(e)};{goods_art_revice};{cutout_goods}")
                         if is_write_txt_log:
                             error_file_path = f"{cutout_goods}/异常说明-出现目录丢失或缺少图片请点开查看原因.txt"
@@ -78,18 +83,21 @@ def handlerFolderDelete(limit_path,goods_art_no_arrays,is_write_txt_log):
                                 f.write(f"请关闭可能正在使用此目录的程序后,为当前货号点击重拍后重试\n")
                         else:
                             raise UnicornException(f"目录检查出现问题:{str(e)},请关闭错误提示中的被占用文件")
-                    except Exception as e:
-                        logger.info(f"抠图前目录删除出现问题:{str(e)};{goods_art_revice};{cutout_goods}")
-                        if is_write_txt_log:
-                            error_file_path = f"{cutout_goods}/异常说明-出现目录丢失或缺少图片请点开查看原因.txt"
-                            with open(error_file_path, 'w', encoding='utf-8') as f:
-                                f.write("目录删除失败\n")
-                                f.write(f"原因: {str(e)}\n")
-                                f.write(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
-                                f.write(f"请检查目录状态后,为当前货号点击重拍后重试\n")
-                        else:
-                            raise UnicornException(f"目录检查出现问题:{str(e)},请关闭错误提示中的被占用文件")
-    return move_folder_array                  
+                    else:
+                        time.sleep(0.5)  # 等待0.5秒后重试
+                except Exception as e:
+                    logger.info(f"抠图前目录删除出现问题:{str(e)};{goods_art_revice};{cutout_goods}")
+                    if is_write_txt_log:
+                        error_file_path = f"{cutout_goods}/异常说明-出现目录丢失或缺少图片请点开查看原因.txt"
+                        with open(error_file_path, 'w', encoding='utf-8') as f:
+                            f.write("目录删除失败\n")
+                            f.write(f"原因: {str(e)}\n")
+                            f.write(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
+                            f.write(f"请检查目录状态后,为当前货号点击重拍后重试\n")
+                    else:
+                        raise UnicornException(f"目录检查出现问题:{str(e)},请关闭错误提示中的被占用文件")
+    
+    return move_folder_array                
 # socket消息发送逻辑处理方法
 async def handlerSend(
     manager: ConnectionManager,