# backend/app/services/file_service.py import os import shutil import uuid from fastapi import UploadFile, HTTPException, status from pathlib import Path from ..core.config import settings class FileService: def __init__(self): self.upload_dir = settings.BASE_DIR / settings.UPLOAD_DIR self.upload_dir.mkdir(exist_ok=True) def save_uploaded_file(self, file: UploadFile) -> tuple[str, str]: """保存上传的文件""" if not file.filename.endswith('.py'): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="只支持.py文件" ) filename = f"{uuid.uuid4().hex}_{file.filename}" file_path = self.upload_dir / filename with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) return filename, str(file_path) def save_code_content(self, code_content: str, name: str) -> tuple[str, str]: """保存代码内容为文件""" filename = f"{uuid.uuid4().hex}_{name.replace(' ', '_')}.py" file_path = self.upload_dir / filename with open(file_path, 'w', encoding='utf-8') as f: f.write(code_content) return filename, str(file_path) def read_file_content(self, file_path: str) -> str: """读取文件内容""" with open(file_path, 'r', encoding='utf-8') as f: return f.read() def delete_file(self, file_path: str): """删除文件""" path = Path(file_path) if path.exists(): path.unlink()