excel.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. from fastapi import APIRouter, File, UploadFile
  2. from fastapi.responses import JSONResponse, FileResponse
  3. from fastapi.exceptions import HTTPException
  4. from werkzeug.utils import secure_filename
  5. from app.utils.excelmerge.conformity import run_conformity
  6. from pathlib import Path
  7. import subprocess
  8. import shutil
  9. import os
  10. router = APIRouter()
  11. ALLOWED_EXTENSIONS = {'xlsx'}
  12. EXCEL_FILES_PATH = 'data/output'
  13. SOURCE_FILES_PATH = 'data/source'
  14. output_path_value = None
  15. def allowed_file(filename):
  16. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  17. def create_dir_if_not_exists(path):
  18. if not os.path.exists(path):
  19. os.makedirs(path)
  20. @router.post('/excel/upload')
  21. async def upload_file(files: list[UploadFile] = File(...)):
  22. if not any(file.filename for file in files):
  23. return JSONResponse(content={"error": "没有文件部分"}, status_code=400)
  24. create_dir_if_not_exists(SOURCE_FILES_PATH)
  25. # 清空SOURCE_FILES_PATH目录
  26. for filename in os.listdir(SOURCE_FILES_PATH):
  27. file_path = os.path.join(SOURCE_FILES_PATH, filename)
  28. try:
  29. if os.path.isfile(file_path) or os.path.islink(file_path):
  30. os.unlink(file_path)
  31. elif os.path.isdir(file_path):
  32. shutil.rmtree(file_path)
  33. except Exception as e:
  34. return JSONResponse(content={"error": "文件处理出错"}, status_code=500)
  35. save_path_list = []
  36. for file in files:
  37. if file.filename == '':
  38. return JSONResponse(content={"error": "没有选择文件"}, status_code=400)
  39. if file and allowed_file(file.filename):
  40. filename = secure_filename(file.filename)
  41. save_path = os.path.join(SOURCE_FILES_PATH, filename)
  42. with open(save_path, 'wb') as buffer:
  43. shutil.copyfileobj(file.file, buffer)
  44. save_path_list.append(save_path)
  45. else:
  46. return JSONResponse(content={"error": "不允许的文件类型"}, status_code=400)
  47. return JSONResponse(content={"message": "文件上传成功", "paths": save_path_list}, status_code=201)
  48. @router.post('/excel/conformity')
  49. async def run_conformity_api():
  50. global output_path_value # 声明全局变量
  51. try:
  52. create_dir_if_not_exists(EXCEL_FILES_PATH)
  53. # 清空EXCEL_FILES_PATH目录
  54. for filename in os.listdir(EXCEL_FILES_PATH):
  55. file_path = os.path.join(EXCEL_FILES_PATH, filename)
  56. try:
  57. if os.path.isfile(file_path) or os.path.islink(file_path):
  58. os.unlink(file_path)
  59. elif os.path.isdir(file_path):
  60. shutil.rmtree(file_path)
  61. except Exception as e:
  62. return JSONResponse(content={"error": "文件处理出错"}, status_code=500)
  63. # 运行方法
  64. output_path = run_conformity()
  65. output_path_value = output_path
  66. return JSONResponse(content={"message": "conformity.py 运行成功", "output_path": str(output_path)}, status_code=200)
  67. except Exception as e:
  68. return JSONResponse(content={"error": str(e)}, status_code=500)
  69. @router.get('/excel/file/status')
  70. async def get_file_status():
  71. try:
  72. return JSONResponse(content={"output_path": str(output_path_value)}, status_code=200)
  73. except Exception as e:
  74. return JSONResponse(content={"error": str(e)}, status_code=500)
  75. @router.get('/excel/download_excel')
  76. async def download_excel():
  77. try:
  78. files = os.listdir(EXCEL_FILES_PATH)
  79. first_file = files[0]
  80. return FileResponse(os.path.join(EXCEL_FILES_PATH, first_file), filename=first_file,
  81. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  82. except FileNotFoundError:
  83. raise HTTPException(status_code=404, detail="文件不存在")
  84. except Exception as e:
  85. raise HTTPException(status_code=500, detail="服务器错误")