Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# This is the main file for our FastAPI application.
|
| 3 |
+
|
| 4 |
+
import io
|
| 5 |
+
import sys
|
| 6 |
+
from fastapi import FastAPI, HTTPException
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
|
| 10 |
+
# Initialize the FastAPI app
|
| 11 |
+
app = 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.
|
| 20 |
+
app.add_middleware(
|
| 21 |
+
CORSMiddleware,
|
| 22 |
+
allow_origins=["*"], # Allows all origins
|
| 23 |
+
allow_credentials=True,
|
| 24 |
+
allow_methods=["*"], # Allows all methods (GET, POST, etc.)
|
| 25 |
+
allow_headers=["*"], # Allows all headers
|
| 26 |
+
)
|
| 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.
|
| 32 |
+
class Code(BaseModel):
|
| 33 |
+
code: str
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# --- API Endpoint ---
|
| 37 |
+
# This defines the endpoint at the path "/execute" that accepts POST requests.
|
| 38 |
+
@app.post("/execute")
|
| 39 |
+
async 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() statements
|
| 44 |
+
old_stdout = sys.stdout
|
| 45 |
+
redirected_output = io.StringIO()
|
| 46 |
+
sys.stdout = redirected_output
|
| 47 |
+
|
| 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_stdout
|
| 56 |
+
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_stdout
|
| 64 |
+
|
| 65 |
+
# Get the captured output from the string buffer
|
| 66 |
+
output = redirected_output.getvalue()
|
| 67 |
+
|
| 68 |
+
# Return the captured output in a JSON response
|
| 69 |
+
return {"output": output}
|
| 70 |
+
|
| 71 |
+
# A simple root endpoint to confirm the API is running
|
| 72 |
+
@app.get("/")
|
| 73 |
+
def read_root():
|
| 74 |
+
return {"message": "Python Code Executor API is running."}
|