| | from fastapi import FastAPI, UploadFile, File, Request |
| | from fastapi.responses import HTMLResponse, JSONResponse |
| | from fastapi.staticfiles import StaticFiles |
| | import os, shutil, json, subprocess |
| |
|
| | app = FastAPI() |
| |
|
| | |
| | UPLOAD_DIR = "/tmp/uploads" |
| | os.makedirs(UPLOAD_DIR, exist_ok=True) |
| |
|
| | |
| | @app.get("/", response_class=HTMLResponse) |
| | async def root(): |
| | with open("index.html", encoding="utf-8") as f: |
| | return f.read() |
| |
|
| | |
| | @app.post("/upload") |
| | async def upload(file: UploadFile = File(...)): |
| | dest = os.path.join(UPLOAD_DIR, file.filename) |
| | with open(dest, "wb") as f: |
| | shutil.copyfileobj(file.file, f) |
| | return {"filename": file.filename} |
| |
|
| | |
| | @app.get("/files") |
| | async def files(): |
| | return os.listdir(UPLOAD_DIR) |
| |
|
| | |
| | @app.post("/run") |
| | async def run_code(request: Request): |
| | data = await request.json() |
| | filename = data.get("filename") |
| | filepath = os.path.join(UPLOAD_DIR, filename) |
| |
|
| | if not os.path.exists(filepath): |
| | return {"output": f"File '{filename}' not found."} |
| |
|
| | try: |
| | result = subprocess.run( |
| | ["python3", filepath], |
| | capture_output=True, |
| | text=True, |
| | timeout=10 |
| | ) |
| | output = result.stdout + result.stderr |
| | return {"output": output} |
| | except subprocess.TimeoutExpired: |
| | return {"output": "Execution timed out."} |
| | except Exception as e: |
| | return {"output": f"Error: {str(e)}"} |
| |
|
| | |
| | @app.post("/setup") |
| | async def setup_config(request: Request): |
| | data = await request.json() |
| | with open("/tmp/setup.json", "w") as f: |
| | json.dump(data, f, indent=2) |
| | return {"status": "ok", "received": data} |
| |
|
| | |
| | app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads") |