Spaces:
Running
Running
File size: 1,832 Bytes
7f340ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import os
import subprocess
import tempfile
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def home():
return jsonify({
"status": "ok",
"message": "Python interpreter backend is running. Send POST requests to /api/run-python"
})
@app.route('/api/run-python', methods=['POST'])
def run_python():
code = request.json.get('code', '')
user_input = request.json.get('input', '')
if not code:
return jsonify({'error': 'No code provided.'}), 400
temp_file_path = None
try:
# Create a temporary file to write the Python code
with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='w', encoding='utf-8') as temp_file:
temp_file.write(code)
temp_file_path = temp_file.name
# Run the Python script as a subprocess
run_process = subprocess.run(
['python', temp_file_path], # The command to run
input=user_input,
capture_output=True,
text=True,
timeout=15 # Set a timeout for safety
)
# Check if the process had errors
if run_process.returncode != 0:
return jsonify({'errors': run_process.stderr})
else:
return jsonify({'output': run_process.stdout})
except subprocess.TimeoutExpired:
return jsonify({'error': 'Code execution timed out (15 seconds limit).'}), 408
except Exception as e:
return jsonify({'error': f"An unexpected error occurred: {str(e)}"}), 500
finally:
# Clean up the temporary file, even if an error occurred
if temp_file_path and os.path.exists(temp_file_path):
os.remove(temp_file_path)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860) |