소스 검색

新增合并Excel下载后删除相关文件

xuyonghao 1 년 전
부모
커밋
29d7f07068
1개의 변경된 파일19개의 추가작업 그리고 2개의 파일을 삭제
  1. 19 2
      app/api/excel.py

+ 19 - 2
app/api/excel.py

@@ -1,4 +1,4 @@
-from fastapi import APIRouter, File, UploadFile, Form
+from fastapi import APIRouter, File, UploadFile, Form, BackgroundTasks
 from fastapi.responses import JSONResponse, FileResponse
 from starlette.websockets import WebSocket
 from app.utils.excelmerge.conformity import run_conformity
@@ -131,12 +131,29 @@ async def ws_excel(websocket: WebSocket, user_id: str):
 
 
 @router.get("/download/{filename}")
-async def download_file(filename: str, user_id: str):
+async def download_file(filename: str, user_id: str, background_tasks: BackgroundTasks):
     user_excel = user_file_path(user_id, EXCEL_FILES_PATH)
+    user_source = user_file_path(user_id, SOURCE_FILES_PATH)
     file_path = os.path.join(user_excel, filename)
 
     if not os.path.exists(file_path):
         return JSONResponse(status_code=404, content={"error": "文件不存在"})
 
+    def delete_files_in_directory(directory):
+        for root, dirs, files in os.walk(directory, topdown=False):
+            for name in files:
+                os.remove(os.path.join(root, name))
+            for name in dirs:
+                os.rmdir(os.path.join(root, name))
+
+    def delete_file():
+        try:
+            delete_files_in_directory(user_excel)
+            delete_files_in_directory(user_source)
+        except OSError as e:
+            print(f"Error deleting file {file_path}: {e}")
+
+    background_tasks.add_task(delete_file)
+
     return FileResponse(file_path, filename=filename,
                         media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')