import contextlib import io import traceback from dotenv import load_dotenv from fastapi import Body, FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel load_dotenv() class CodeExecutionRequest(BaseModel): code: str def _execute_python(code: str) -> dict[str, object]: stdout_buffer = io.StringIO() stderr_buffer = io.StringIO() try: with contextlib.redirect_stdout(stdout_buffer), contextlib.redirect_stderr(stderr_buffer): exec(code) except Exception: return { "stdout": stdout_buffer.getvalue(), "stderr": stderr_buffer.getvalue(), "error": traceback.format_exc(), "code": code, } return { "stdout": stdout_buffer.getvalue(), "stderr": stderr_buffer.getvalue(), "error": None, "code": code, } app = FastAPI( title="Infina Code Sandbox API", description="Bu API, gonderilen Python kodlarini calistiran sandbox ortami saglar.", version="1.0.0", docs_url="/swagger", ) # ------------------------ # CORS ayarları (tüm origin'lere izin) # ------------------------ app.add_middleware( CORSMiddleware, allow_origins=["*"], # tüm origin'lere izin allow_credentials=True, allow_methods=["*"], # tüm HTTP metotlarına izin allow_headers=["*"], # tüm header'lara izin ) @app.get("/") async def root(): return {"message": "API calisiyor. Test icin /swagger veya /redoc adresini ziyaret edin."} @app.post("/execute") async def execute_code(payload: CodeExecutionRequest): return _execute_python(payload.code) @app.post("/execute/raw") async def execute_code_raw(code: str = Body(..., media_type="text/plain", embed=False)): return _execute_python(code) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="localhost", port=5556)