-
-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathmain.py
More file actions
40 lines (34 loc) · 1015 Bytes
/
main.py
File metadata and controls
40 lines (34 loc) · 1015 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import traceback
import io
import contextlib
app = FastAPI(title="Code Interpreter API")
@app.get("/")
async def root():
return {"message": "🚀 Code Interpreter API is running"}
@app.post("/run")
async def run_code(request: Request):
"""
简易 Python 代码执行接口
Body 例子:
{
"code": "print(1+1)"
}
"""
try:
data = await request.json()
code = data.get("code", "")
if not code:
return JSONResponse({"error": "No code provided"}, status_code=400)
# 捕获代码输出
output_buffer = io.StringIO()
with contextlib.redirect_stdout(output_buffer):
exec(code, {})
result = output_buffer.getvalue()
return {"result": result.strip()}
except Exception as e:
return JSONResponse({
"error": str(e),
"traceback": traceback.format_exc()
}, status_code=500)