samarth upadhyay commited on
Commit
9304b86
·
verified ·
1 Parent(s): b17aebc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -53
app.py CHANGED
@@ -1,6 +1,4 @@
1
- import os
2
  import subprocess
3
- import tempfile
4
  import sys
5
  from flask import Flask, request, jsonify
6
  from flask_cors import CORS
@@ -10,7 +8,7 @@ CORS(app)
10
 
11
  @app.route('/')
12
  def home():
13
- return jsonify({"status": "ok", "message": "API Running. POST to /api/run-python or /api/run-sql"})
14
 
15
  def run_command(command, input_text=None, timeout=15):
16
  """Helper to run shell commands safely"""
@@ -22,10 +20,8 @@ def run_command(command, input_text=None, timeout=15):
22
  text=True,
23
  timeout=timeout
24
  )
25
- # Return stdout if success, stderr if fail (or both)
26
  output = run_process.stdout
27
  if run_process.stderr:
28
- # Append stderr to output so user sees errors
29
  output += "\n--- Error Log ---\n" + run_process.stderr
30
  return output
31
  except subprocess.TimeoutExpired:
@@ -36,24 +32,15 @@ def run_command(command, input_text=None, timeout=15):
36
  @app.route('/api/run-python', methods=['POST'])
37
  def run_python():
38
  code = request.json.get('code', '')
39
- user_input = request.json.get('input', '') # Optional stdin input
40
 
41
  if not code: return jsonify({'output': 'No code provided'}), 400
42
 
43
- # Write code to temp file
44
- temp_path = None
45
- try:
46
- with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='w', encoding='utf-8') as f:
47
- f.write(code)
48
- temp_path = f.name
49
-
50
- # Run python using the current environment's python executable
51
- output = run_command([sys.executable, temp_path], input_text=user_input)
52
- return jsonify({'output': output})
53
-
54
- finally:
55
- if temp_path and os.path.exists(temp_path):
56
- os.remove(temp_path)
57
 
58
  @app.route('/api/run-sql', methods=['POST'])
59
  def run_sql():
@@ -63,43 +50,31 @@ def run_sql():
63
 
64
  if not sql_code: return jsonify({'output': 'No SQL code provided'}), 400
65
 
66
- # Write SQL to temp file (safer for some CLI tools)
67
- temp_sql_path = None
68
- try:
69
- with tempfile.NamedTemporaryFile(suffix=".sql", delete=False, mode='w', encoding='utf-8') as f:
70
- f.write(sql_code)
71
- temp_sql_path = f.name
72
-
73
- output = ""
74
-
75
- if db_type == 'sqlite':
76
- # Run sqlite3 against an in-memory DB
77
- # We pass the SQL content via stdin
78
- cmd = ["sqlite3", ":memory:"]
79
- output = run_command(cmd, input_text=sql_code)
80
-
81
- elif db_type in ['postgres', 'postgresql']:
82
- # Run psql using the 'playground' user defined in start.sh
83
- # -f runs the file provided
84
- cmd = ["psql", "-h", "localhost", "-U", "playground", "-d", "playground", "-f", temp_sql_path]
85
- output = run_command(cmd)
86
 
87
- elif db_type == 'mysql':
88
- # Run mysql using the 'playground' user defined in start.sh
89
- # -t forces ASCII table output even in non-interactive mode
90
- cmd = ["mysql", "-h", "localhost", "-u", "playground", "playground", "-t"]
91
- # Pass SQL via stdin
92
- output = run_command(cmd, input_text=sql_code)
93
 
94
- else:
95
- return jsonify({'output': 'Unsupported database type. Use sqlite, postgres, or mysql.'}), 400
 
 
 
96
 
97
- return jsonify({'output': output})
 
98
 
99
- finally:
100
- if temp_sql_path and os.path.exists(temp_sql_path):
101
- os.remove(temp_sql_path)
102
 
 
 
103
  if __name__ == '__main__':
104
- # Hugging Face expects port 7860
105
  app.run(host="0.0.0.0", port=7860)
 
 
1
  import subprocess
 
2
  import sys
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
 
8
 
9
  @app.route('/')
10
  def home():
11
+ return jsonify({"status": "ok", "message": "API Running (Gunicorn Enabled)"})
12
 
13
  def run_command(command, input_text=None, timeout=15):
14
  """Helper to run shell commands safely"""
 
20
  text=True,
21
  timeout=timeout
22
  )
 
23
  output = run_process.stdout
24
  if run_process.stderr:
 
25
  output += "\n--- Error Log ---\n" + run_process.stderr
26
  return output
27
  except subprocess.TimeoutExpired:
 
32
  @app.route('/api/run-python', methods=['POST'])
33
  def run_python():
34
  code = request.json.get('code', '')
35
+ user_input = request.json.get('input', '')
36
 
37
  if not code: return jsonify({'output': 'No code provided'}), 400
38
 
39
+ # Run python using -c to avoid temp files
40
+ # We pass the code as the argument to -c
41
+ cmd = [sys.executable, "-c", code]
42
+ output = run_command(cmd, input_text=user_input)
43
+ return jsonify({'output': output})
 
 
 
 
 
 
 
 
 
44
 
45
  @app.route('/api/run-sql', methods=['POST'])
46
  def run_sql():
 
50
 
51
  if not sql_code: return jsonify({'output': 'No SQL code provided'}), 400
52
 
53
+ output = ""
54
+
55
+ if db_type == 'sqlite':
56
+ # SQL via Stdin -> SQLite
57
+ cmd = ["sqlite3", ":memory:"]
58
+ output = run_command(cmd, input_text=sql_code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ elif db_type in ['postgres', 'postgresql']:
61
+ # SQL via Stdin -> Psql
62
+ # We do not use -f anymore. Psql reads from stdin by default.
63
+ cmd = ["psql", "-h", "localhost", "-U", "playground", "-d", "playground"]
64
+ output = run_command(cmd, input_text=sql_code)
 
65
 
66
+ elif db_type == 'mysql':
67
+ # SQL via Stdin -> MySQL
68
+ # -t forces table output
69
+ cmd = ["mysql", "-h", "localhost", "-u", "playground", "playground", "-t"]
70
+ output = run_command(cmd, input_text=sql_code)
71
 
72
+ else:
73
+ return jsonify({'output': 'Unsupported database type.'}), 400
74
 
75
+ return jsonify({'output': output})
 
 
76
 
77
+ # Note: app.run() is no longer needed here as Gunicorn handles it,
78
+ # but we keep it for local debugging if you run python app.py directly.
79
  if __name__ == '__main__':
 
80
  app.run(host="0.0.0.0", port=7860)