I want a Cloudflare Worker code which takes a JSON file as input and from the 'code' key's value, it must take the value, execute the code and return the terminal output as response
Can I at least get a confirmation of whether this is possible or not?!
# src/entry.py
from js import Response
def on_fetch(request):
try:
# Get the request body (assuming it's JSON)
body = request.json()
code_to_execute = body.get("code", "")
# Execute the Python code
import subprocess
result = subprocess.run(["python", "-c", code_to_execute], capture_output=True, text=True)
# Return the terminal output as the response
return Response.new(result.stdout)
except Exception as e:
return Response.new(f"Error executing code: {str(e)}", {"status": 500})
This is the code I tried and is showing this error:
Error executing@ code: 'PyodideFuture' object has no attribute 'get'
Cloudflare Workers are designed to handle tasks like HTTP request and response handling, not to execute arbitrary code due to security and performance constraints. You can instead use tools like Pyodide (which compiles Python to WebAssembly) to run Python code in the browser.