Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Form
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
import tempfile
|
| 5 |
+
import os
|
| 6 |
+
import importlib.util
|
| 7 |
+
|
| 8 |
+
CACHE_DIR = "/home/user/.cache_packages"
|
| 9 |
+
|
| 10 |
+
# Ensure the cache dir exists
|
| 11 |
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 12 |
+
|
| 13 |
+
# Add cache dir to Python path
|
| 14 |
+
if CACHE_DIR not in sys.path:
|
| 15 |
+
sys.path.insert(0, CACHE_DIR)
|
| 16 |
+
|
| 17 |
+
app = FastAPI()
|
| 18 |
+
|
| 19 |
+
def install_package_if_needed(package_name: str):
|
| 20 |
+
"""Install a package to CACHE_DIR only if not already installed."""
|
| 21 |
+
if importlib.util.find_spec(package_name) is None:
|
| 22 |
+
subprocess.check_call([
|
| 23 |
+
sys.executable, "-m", "pip", "install",
|
| 24 |
+
"--target", CACHE_DIR, package_name
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
@app.post("/run")
|
| 28 |
+
def run_code(code: str = Form(...)):
|
| 29 |
+
try:
|
| 30 |
+
lines = code.strip().split("\n")
|
| 31 |
+
|
| 32 |
+
# Separate pip installs from Python code
|
| 33 |
+
pip_commands = [line.strip() for line in lines if line.strip().startswith("pip install")]
|
| 34 |
+
python_code_lines = [line for line in lines if not line.strip().startswith("pip install")]
|
| 35 |
+
|
| 36 |
+
# Handle pip installs
|
| 37 |
+
for cmd in pip_commands:
|
| 38 |
+
parts = cmd.split()
|
| 39 |
+
for pkg in parts[2:]: # Skip 'pip' and 'install'
|
| 40 |
+
try:
|
| 41 |
+
install_package_if_needed(pkg)
|
| 42 |
+
except subprocess.CalledProcessError as e:
|
| 43 |
+
return {"stdout": "", "stderr": f"Error installing: {pkg}\n{str(e)}"}
|
| 44 |
+
|
| 45 |
+
# Save Python code to temp file
|
| 46 |
+
python_code = "\n".join(python_code_lines)
|
| 47 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as temp_file:
|
| 48 |
+
temp_file.write(python_code.encode())
|
| 49 |
+
temp_path = temp_file.name
|
| 50 |
+
|
| 51 |
+
# Run Python code
|
| 52 |
+
result = subprocess.run(
|
| 53 |
+
[sys.executable, temp_path],
|
| 54 |
+
capture_output=True,
|
| 55 |
+
text=True
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
os.unlink(temp_path) # Clean up
|
| 59 |
+
|
| 60 |
+
return {
|
| 61 |
+
"stdout": result.stdout,
|
| 62 |
+
"stderr": result.stderr
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return {"error": str(e)}
|