Skip to content

Commit 1ffd7bc

Browse files
committed
Update backend to use global namespace and improve error handling
1 parent 942a3ea commit 1ffd7bc

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

backend/app/main.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
expose_headers=["*"]
2525
)
2626

27+
# Global namespace for code execution
28+
GLOBAL_NAMESPACE = {}
29+
2730
class CodeRequest(BaseModel):
2831
code: str
2932

@@ -38,11 +41,26 @@ async def health_check():
3841
@app.post("/execute")
3942
async def execute_code(request: CodeRequest):
4043
try:
44+
# First try to compile the code to catch syntax errors
45+
try:
46+
compiled_code = compile(request.code, '<string>', 'exec')
47+
except SyntaxError as e:
48+
return JSONResponse(
49+
status_code=400,
50+
content={"error": str(e)},
51+
headers={
52+
"Access-Control-Allow-Origin": "*",
53+
"Access-Control-Allow-Methods": "POST, OPTIONS",
54+
"Access-Control-Allow-Headers": "*"
55+
}
56+
)
57+
4158
# Capture stdout
4259
output = StringIO()
4360
with contextlib.redirect_stdout(output):
44-
# Execute the code in a safe environment
45-
exec(request.code, {}, {})
61+
# Execute the code in the global namespace
62+
exec(compiled_code, GLOBAL_NAMESPACE)
63+
4664
return JSONResponse(
4765
content={"output": output.getvalue()},
4866
headers={
@@ -54,7 +72,7 @@ async def execute_code(request: CodeRequest):
5472
except Exception as e:
5573
error_details = {
5674
"error": str(e),
57-
"traceback": traceback.format_exc()
75+
"type": e.__class__.__name__
5876
}
5977
return JSONResponse(
6078
status_code=400,

0 commit comments

Comments
 (0)