file_service.py 1.6 KB

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