Devity4756 commited on
Commit
b377e25
·
verified ·
1 Parent(s): 5beb012

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -28
app.py CHANGED
@@ -188,7 +188,6 @@ def secure_execute_flask_code(app_instance, code, log_func, request_obj):
188
  def run_flask_app(app_name: str, code: str):
189
  """Start a Flask app on a dedicated port"""
190
  global next_port
191
-
192
  log_buffer = io.StringIO()
193
  flask_logs[app_name] = log_buffer
194
  port = next_port
@@ -201,56 +200,58 @@ def run_flask_app(app_name: str, code: str):
201
  print(f"[{app_name}] {msg}")
202
 
203
  try:
204
- # Validate code first
205
  is_valid, validation_msg = validate_flask_code(code)
206
  if not is_valid:
207
  log(f"Code validation failed: {validation_msg}")
208
- return
209
 
210
  from flask import Flask, request
211
  local_flask = Flask(app_name)
212
 
213
- # Default route
214
  @local_flask.route("/")
215
  def home():
216
  return f"Hello from {app_name}!<br><br>App is running successfully."
217
 
218
- # Secure execution of user code
219
  success, exec_msg = secure_execute_flask_code(local_flask, code, log, request)
220
  if not success:
221
  log(f"Failed to execute code: {exec_msg}")
222
- return
223
 
224
- # Start the Flask app in a separate thread
225
  def run_app():
226
- try:
227
- local_flask.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
228
- except Exception as e:
229
- return f"Error running Flask app: {e}"
230
-
 
231
  thread = threading.Thread(target=run_app, daemon=True)
232
  thread.start()
233
-
234
  flask_apps[app_name] = local_flask
235
-
236
- # Get the correct URLs
237
  local_ip = get_local_ip()
238
  local_url = f"http://{local_ip}:{port}"
239
-
240
- # For Hugging Face Spaces
241
  if "hf.space" in public_url:
242
  space_id = public_url.split("https://")[1].split(".hf.space")[0]
243
  live_url = f"https://{space_id}.hf.space/proxy/{port}/"
244
  else:
245
  live_url = f"{public_url}/proxy/{port}/"
246
-
247
  log(f"Started Flask app: {app_name} on port {port}")
248
  log(f"Local URL: {local_url}")
249
  log(f"Live URL: {live_url}")
250
- log("App is now live and accessible!")
251
-
252
  except Exception as e:
253
  log(f"Error starting Flask app {app_name}: {e}")
 
 
 
 
 
 
 
 
 
 
254
 
255
  def run_python_app(file_path: str):
256
  """Run a regular Python application"""
@@ -337,6 +338,26 @@ def run_command(cmd: str):
337
  raw_cmd = parts[0].lower()
338
  args = parts[1] if len(parts) > 1 else ""
339
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  try:
341
  # === STOP running process ===
342
  if raw_cmd == "close":
@@ -458,16 +479,10 @@ def run_command(cmd: str):
458
 
459
  # === Normal shell command ===
460
  try:
461
- # Avoid shell=True for common commands
462
- if raw_cmd == "ls":
463
- cmd_parts = ['ls', '-l'] if not args else ['ls', '-l', args]
464
- elif raw_cmd == "cat" and args:
465
- cmd_parts = ['cat', expand_path(args)]
466
- else:
467
- cmd_parts = cmd.split() # Split for safer execution
468
  running_process = subprocess.Popen(
469
  cmd_parts,
470
- shell=False, # Prefer shell=False for safety
471
  cwd=current_dir,
472
  stdout=subprocess.PIPE,
473
  stderr=subprocess.PIPE,
 
188
  def run_flask_app(app_name: str, code: str):
189
  """Start a Flask app on a dedicated port"""
190
  global next_port
 
191
  log_buffer = io.StringIO()
192
  flask_logs[app_name] = log_buffer
193
  port = next_port
 
200
  print(f"[{app_name}] {msg}")
201
 
202
  try:
 
203
  is_valid, validation_msg = validate_flask_code(code)
204
  if not is_valid:
205
  log(f"Code validation failed: {validation_msg}")
206
+ return f"Failed to start Flask app: {validation_msg}"
207
 
208
  from flask import Flask, request
209
  local_flask = Flask(app_name)
210
 
 
211
  @local_flask.route("/")
212
  def home():
213
  return f"Hello from {app_name}!<br><br>App is running successfully."
214
 
 
215
  success, exec_msg = secure_execute_flask_code(local_flask, code, log, request)
216
  if not success:
217
  log(f"Failed to execute code: {exec_msg}")
218
+ return f"Failed to start Flask app: {exec_msg}"
219
 
 
220
  def run_app():
221
+ try:
222
+ local_flask.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
223
+ except Exception as e:
224
+ log(f"Error running Flask app: {e}")
225
+ return f"Error running Flask app: {e}"
226
+
227
  thread = threading.Thread(target=run_app, daemon=True)
228
  thread.start()
 
229
  flask_apps[app_name] = local_flask
230
+
 
231
  local_ip = get_local_ip()
232
  local_url = f"http://{local_ip}:{port}"
 
 
233
  if "hf.space" in public_url:
234
  space_id = public_url.split("https://")[1].split(".hf.space")[0]
235
  live_url = f"https://{space_id}.hf.space/proxy/{port}/"
236
  else:
237
  live_url = f"{public_url}/proxy/{port}/"
238
+
239
  log(f"Started Flask app: {app_name} on port {port}")
240
  log(f"Local URL: {local_url}")
241
  log(f"Live URL: {live_url}")
242
+ return f"Started Flask app: {app_name}\nLocal URL: {local_url}\nLive URL: {live_url}"
 
243
  except Exception as e:
244
  log(f"Error starting Flask app {app_name}: {e}")
245
+ return f"Error starting Flask app: {e}"
246
+
247
+ def is_flask_app(file_path):
248
+ """Check if a Python file contains Flask code."""
249
+ try:
250
+ with open(file_path, 'r', encoding='utf-8') as f:
251
+ content = f.read()
252
+ return bool(re.search(r'@app\.route', content))
253
+ except Exception:
254
+ return False
255
 
256
  def run_python_app(file_path: str):
257
  """Run a regular Python application"""
 
338
  raw_cmd = parts[0].lower()
339
  args = parts[1] if len(parts) > 1 else ""
340
 
341
+ try:
342
+ # === STOP running process ===
343
+ if raw_cmd == "close":
344
+ if running_process and running_process.poll() is None:
345
+ running_process.terminate()
346
+ running_process = None
347
+ return f"$ {cmd}\n\nStopped running process.", "", None
348
+ return f"$ {cmd}\n\nNo active process to stop.", "", None
349
+ def run_command(cmd: str):
350
+ """Handle terminal-like commands including Flask and Python apps"""
351
+ global current_dir, running_process
352
+ cmd = cmd.strip() # Remove leading/trailing whitespace
353
+ if not cmd:
354
+ return "No command provided", "", None
355
+
356
+ # Split command into command and arguments (maxsplit=1 for commands with spaces)
357
+ parts = cmd.split(maxsplit=1)
358
+ raw_cmd = parts[0].lower()
359
+ args = parts[1] if len(parts) > 1 else ""
360
+
361
  try:
362
  # === STOP running process ===
363
  if raw_cmd == "close":
 
479
 
480
  # === Normal shell command ===
481
  try:
482
+ cmd_parts = ['ls', '-l'] if raw_cmd == "ls" and not args else cmd.split()
 
 
 
 
 
 
483
  running_process = subprocess.Popen(
484
  cmd_parts,
485
+ shell=False, # Avoid shell=True for safety
486
  cwd=current_dir,
487
  stdout=subprocess.PIPE,
488
  stderr=subprocess.PIPE,