Spaces:
Sleeping
Sleeping
Update backend.py
Browse files- backend.py +35 -29
backend.py
CHANGED
|
@@ -1,29 +1,35 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
| 2 |
-
import subprocess
|
| 3 |
-
|
| 4 |
-
app = Flask(__name__)
|
| 5 |
-
|
| 6 |
-
@app.route("/run", methods=["POST"])
|
| 7 |
-
def run_code():
|
| 8 |
-
try:
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import subprocess
|
| 3 |
+
|
| 4 |
+
app = Flask(__name__)
|
| 5 |
+
|
| 6 |
+
@app.route("/run", methods=["POST"])
|
| 7 |
+
def run_code():
|
| 8 |
+
try:
|
| 9 |
+
# Ensure request contains JSON data
|
| 10 |
+
if not request.is_json:
|
| 11 |
+
return jsonify({"output": "Invalid request. Expecting JSON format."}), 400
|
| 12 |
+
|
| 13 |
+
data = request.get_json()
|
| 14 |
+
code = data.get("code", "")
|
| 15 |
+
|
| 16 |
+
if not code.strip():
|
| 17 |
+
return jsonify({"output": "No code provided!"}), 400
|
| 18 |
+
|
| 19 |
+
# Run Python code in a subprocess
|
| 20 |
+
process = subprocess.run(
|
| 21 |
+
["python", "-c", code],
|
| 22 |
+
capture_output=True,
|
| 23 |
+
text=True
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
output = process.stdout.strip() if process.stdout else process.stderr.strip()
|
| 27 |
+
|
| 28 |
+
return jsonify({"output": output})
|
| 29 |
+
|
| 30 |
+
except Exception as e:
|
| 31 |
+
return jsonify({"output": f"Error: {str(e)}"}), 500
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
app.run(host="0.0.0.0", port=5000, debug=True)
|