sathish2352/compiler
0
1# app.py2# This is the main file for our FastAPI application.3 4import io5import sys6from fastapi import FastAPI, HTTPException7from pydantic import BaseModel8from fastapi.middleware.cors import CORSMiddleware9 10# Initialize the FastAPI app11app = FastAPI(12 title="Python Code Executor API",13 description="An API to execute Python code securely and return the output.",14 version="1.0.0",15)16 17# --- CORS Middleware ---18# This is important to allow your front-end website (running on a different domain)19# to communicate with this API. We'll allow all origins for simplicity.20app.add_middleware(21 CORSMiddleware,22 allow_origins=["*"], # Allows all origins23 allow_credentials=True,24 allow_methods=["*"], # Allows all methods (GET, POST, etc.)25 allow_headers=["*"], # Allows all headers26)27 28 29# --- Request Body Model ---30# This Pydantic model defines the structure of the JSON we expect in the request.31# It ensures that the incoming data has a "code" field which is a string.32class Code(BaseModel):33 code: str34 35 36# --- API Endpoint ---37# This defines the endpoint at the path "/execute" that accepts POST requests.38@app.post("/execute")39async def execute_python_code(code_payload: Code):40 """41 Executes the provided Python code and returns its output or any errors.42 """43 # Create a string buffer to capture the output of the print() statements44 old_stdout = sys.stdout45 redirected_output = io.StringIO()46 sys.stdout = redirected_output47 48 try:49 # The exec() function executes the Python code passed as a string.50 # We pass an empty dictionary for globals and locals for a cleaner scope.51 exec(code_payload.code, {}, {})52 except Exception as e:53 # If any error occurs during execution, restore stdout and raise an HTTPException.54 # This will be sent back to the user as a proper error response.55 sys.stdout = old_stdout56 raise HTTPException(57 status_code=400,58 detail=f"Error executing code: {str(e)}"59 )60 finally:61 # This 'finally' block ensures that we always restore the original stdout,62 # even if an error occurred. This is crucial for the server's stability.63 sys.stdout = old_stdout64 65 # Get the captured output from the string buffer66 output = redirected_output.getvalue()67 68 # Return the captured output in a JSON response69 return {"output": output}70 71# A simple root endpoint to confirm the API is running72@app.get("/")73def read_root():74 return {"message": "Python Code Executor API is running."}75 