From d05dc5c5c1daebfdb4803d7075ff846ad7b3be25 Mon Sep 17 00:00:00 2001
From: xuyonghao <898441624@qq.com>
Date: 星期一, 30 十二月 2024 17:05:36 +0800
Subject: [PATCH] 使用调度器定时删除文件

---
 app/utils/excelmerge/conformity.py |   42 +++++++++++++++++++++++++++++++++++++-----
 1 files changed, 37 insertions(+), 5 deletions(-)

diff --git a/app/utils/excelmerge/conformity.py b/app/utils/excelmerge/conformity.py
index bca8868..aa14775 100644
--- a/app/utils/excelmerge/conformity.py
+++ b/app/utils/excelmerge/conformity.py
@@ -1,6 +1,12 @@
-from openpyxl import load_workbook
-from datetime import datetime
 import os
+import random
+import shutil
+import string
+
+from datetime import datetime
+from openpyxl import load_workbook
+from Log import logger
+from main import scheduler
 
 
 def clear_blank_rows(sheet):
@@ -17,6 +23,17 @@
                 source_sheet.cell(row=row, column=col).value for col in range(4, source_sheet.max_column + 1)):
             target_sheet.append(
                 [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):
+    def delete_file():
+        try:
+            if os.path.exists(file_path):
+                os.remove(file_path)
+        except Exception as e:
+            logger.error(f"瀹氭椂鍒犻櫎Excel鏂囦欢鏃跺彂鐢熼敊璇�: {e}")
+
+    scheduler.add_job(delete_file, 'interval', minutes=delay_minutes, id=f"delete_{file_path}")
 
 
 def run_conformity(file_path, print_path):
@@ -55,11 +72,26 @@
                     template_sheets[name].cell(row=i, column=1).value = i - start_row + 1
 
         timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
-        output_path = os.path.join(print_path, f'{timestamp}.xlsx')
+        random_string = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(5))
+        file_name = f'{random_string}_{timestamp}'
+        output_path = os.path.join(print_path, f'{file_name}.xlsx')
         template_excel.save(output_path)
         template_excel.close()
 
-        return True
+        delete_file_after_delay(output_path, 3)
+
+        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}")
+
+        return file_name
     except Exception as e:
         print(f"璇诲彇鏁版嵁鍙戠敓閿欒: {e}")
-        return False
+        return None

--
Gitblit v1.8.0