Sfoglia il codice sorgente

定时删除没有被下载的excel文件

xuyonghao 1 anno fa
parent
commit
93501af060
1 ha cambiato i file con 26 aggiunte e 8 eliminazioni
  1. 26 8
      app/utils/excelmerge/conformity.py

+ 26 - 8
app/utils/excelmerge/conformity.py

@@ -2,9 +2,12 @@ import os
 import random
 import shutil
 import string
-from datetime import datetime
+import threading
+import time
 
+from datetime import datetime
 from openpyxl import load_workbook
+from Log import logger
 
 
 def clear_blank_rows(sheet):
@@ -23,6 +26,20 @@ def copy_data(source_sheet, target_sheet, start_row):
                 [source_sheet.cell(row=row, column=col).value for col in range(1, source_sheet.max_column + 1)])
 
 
+def delete_file_after_delay(file_path, delay_minutes):
+    delay_seconds = delay_minutes * 60
+
+    def delete_file():
+        time.sleep(delay_seconds)
+        try:
+            if os.path.exists(file_path):
+                os.remove(file_path)
+        except Exception as e:
+            logger.error(f"定时删除Excel文件时发生错误: {e}")
+
+    threading.Thread(target=delete_file).start()
+
+
 def run_conformity(file_path, print_path):
     try:
         # 加载模板文件
@@ -65,17 +82,18 @@ def run_conformity(file_path, print_path):
         template_excel.save(output_path)
         template_excel.close()
 
-        # 合并完成后删除无用文件
-        for filename in os.listdir(file_path):
-            file_path_full = os.path.join(file_path, filename)
-            try:
+        delete_file_after_delay(output_path, 5)
+
+        try:
+            for filename in os.listdir(file_path):
+                file_path_full = os.path.join(file_path, filename)
                 if os.path.isfile(file_path_full) or os.path.islink(file_path_full):
                     os.unlink(file_path_full)
                 elif os.path.isdir(file_path_full):
                     shutil.rmtree(file_path_full)
-                os.rmdir(file_path)
-            except Exception as e:
-                print(f"删除文件时发生错误: {e}")
+            os.rmdir(file_path)
+        except Exception as e:
+            print(f"删除文件时发生错误: {e}")
 
         return file_name
     except Exception as e: