File tree Expand file tree Collapse file tree 1 file changed +21
-3
lines changed Expand file tree Collapse file tree 1 file changed +21
-3
lines changed Original file line number Diff line number Diff line change 2424 expose_headers = ["*" ]
2525)
2626
27+ # Global namespace for code execution
28+ GLOBAL_NAMESPACE = {}
29+
2730class CodeRequest (BaseModel ):
2831 code : str
2932
@@ -38,11 +41,26 @@ async def health_check():
3841@app .post ("/execute" )
3942async 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 ,
You can’t perform that action at this time.
0 commit comments