file_service.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # backend/app/services/file_service.py
  2. import os
  3. import shutil
  4. import uuid
  5. from fastapi import UploadFile, HTTPException, status
  6. class FileService:
  7. def __init__(self, upload_dir: str):
  8. self.upload_dir = upload_dir
  9. os.makedirs(upload_dir, exist_ok=True)
  10. def save_uploaded_file(self, file: UploadFile) -> tuple[str, str]:
  11. """保存上传的文件"""
  12. if not file.filename.endswith('.py'):
  13. raise HTTPException(
  14. status_code=status.HTTP_400_BAD_REQUEST,
  15. detail="只支持.py文件"
  16. )
  17. filename = f"{uuid.uuid4().hex}_{file.filename}"
  18. file_path = os.path.join(self.upload_dir, filename)
  19. with open(file_path, "wb") as buffer:
  20. shutil.copyfileobj(file.file, buffer)
  21. return filename, file_path
  22. def save_code_content(self, code_content: str, name: str) -> tuple[str, str]:
  23. """保存代码内容为文件"""
  24. filename = f"{uuid.uuid4().hex}_{name.replace(' ', '_')}.py"
  25. file_path = os.path.join(self.upload_dir, filename)
  26. with open(file_path, 'w', encoding='utf-8') as f:
  27. f.write(code_content)
  28. return filename, file_path
  29. def read_file_content(self, file_path: str) -> str:
  30. """读取文件内容"""
  31. with open(file_path, 'r', encoding='utf-8') as f:
  32. return f.read()
  33. def delete_file(self, file_path: str):
  34. """删除文件"""
  35. if os.path.exists(file_path):
  36. os.remove(file_path)