# backend/app/services/file_service.py import os import shutil import uuid from fastapi import UploadFile, HTTPException, status class FileService: def __init__(self, upload_dir: str): self.upload_dir = upload_dir os.makedirs(upload_dir, 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 = os.path.join(self.upload_dir, filename) with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) return filename, 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 = os.path.join(self.upload_dir, filename) with open(file_path, 'w', encoding='utf-8') as f: f.write(code_content) return filename, 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): """删除文件""" if os.path.exists(file_path): os.remove(file_path)