broadfield-dev commited on
Commit
b93e800
·
verified ·
1 Parent(s): 7d4b552

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, render_template_string
2
+ import subprocess
3
+ import sys
4
+ import os
5
+ from io import StringIO
6
+ import contextlib
7
+
8
+ app = Flask(__name__)
9
+
10
+ # HTML template for the code input and output display
11
+ HTML_TEMPLATE = """
12
+ <!DOCTYPE html>
13
+ <html>
14
+ <head>
15
+ <title>Python Code Runner</title>
16
+ <style>
17
+ body { font-family: Arial, sans-serif; margin: 20px; }
18
+ textarea { width: 100%; height: 300px; }
19
+ pre { background: #f4f4f4; padding: 10px; border: 1px solid #ddd; }
20
+ .error { color: red; }
21
+ </style>
22
+ </head>
23
+ <body>
24
+ <h1>Python Code Runner</h1>
25
+ <form method="POST" action="/">
26
+ <textarea name="code" placeholder="Paste your Python code here">{{ code }}</textarea><br>
27
+ <input type="submit" value="Run Code">
28
+ </form>
29
+ {% if output %}
30
+ <h2>Output:</h2>
31
+ <pre>{{ output }}</pre>
32
+ {% endif %}
33
+ {% if error %}
34
+ <h2 class="error">Error:</h2>
35
+ <pre class="error">{{ error }}</pre>
36
+ {% endif %}
37
+ </body>
38
+ </html>
39
+ """
40
+
41
+ @app.route("/", methods=["GET", "POST"])
42
+ def run_code():
43
+ code = ""
44
+ output = ""
45
+ error = ""
46
+
47
+ if request.method == "POST":
48
+ code = request.form.get("code", "")
49
+
50
+ # Write the code to a temporary file
51
+ temp_file = "temp_code.py"
52
+ with open(temp_file, "w") as f:
53
+ f.write(code)
54
+
55
+ try:
56
+ # Run the code in a subprocess with restricted environment
57
+ result = subprocess.run(
58
+ [sys.executable, temp_file],
59
+ capture_output=True,
60
+ text=True,
61
+ timeout=10 # Limit execution time to 10 seconds
62
+ )
63
+ output = result.stdout
64
+ error = result.stderr
65
+ except subprocess.TimeoutExpired:
66
+ error = "Execution timed out after 10 seconds."
67
+ except Exception as e:
68
+ error = f"An error occurred: {str(e)}"
69
+ finally:
70
+ # Clean up the temporary file
71
+ if os.path.exists(temp_file):
72
+ os.remove(temp_file)
73
+
74
+ return render_template_string(HTML_TEMPLATE, code=code, output=output, error=error)
75
+
76
+ if __name__ == "__main__":
77
+ app.run(debug=True, host="0.0.0.0", port=5000)