Contenidos
Main.py
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import os import threading import time from flask import Flask, jsonify app = Flask(__name__) # Variable global para almacenar el estado del hilo thread_output = [] # Función que se ejecuta en un hilo separado def background_task(): global thread_output for i in range(1, 6): thread_output.append(f'Hilo en ejecución: {i}') time.sleep(1) # Pausa de 1 segundo thread_output.append('Fin del hilo') @app.route('/') def index(): return ''' <h1>Ejecutar Hilo</h1> <button onclick="startThread()">Iniciar Hilo</button> <h2>Salida del Hilo:</h2> <pre id="output"></pre> <script> function startThread() { fetch('/start-thread') .then(response => response.json()) .then(data => { if (data.started) { document.getElementById('output').innerText = 'Hilo iniciado...'; checkThreadOutput(); } }); } function checkThreadOutput() { fetch('/thread-output') .then(response => response.json()) .then(data => { document.getElementById('output').innerText = data.output.join('\\n'); if (!data.finished) { setTimeout(checkThreadOutput, 1000); } }); } </script> ''' @app.route('/start-thread') def start_thread(): # Iniciar el hilo solo si no está ya en ejecución if not any(thread.name == 'BackgroundThread' for thread in threading.enumerate()): thread = threading.Thread(target=background_task, name='BackgroundThread') thread.start() return jsonify({'started': True}) else: return jsonify({'started': False}) @app.route('/thread-output') def get_thread_output(): global thread_output finished = 'Fin del hilo' in thread_output return jsonify({'output': thread_output, 'finished': finished}) def main(): app.run(port=int(os.environ.get('PORT', 5000)), debug=True) if __name__ == "__main__": main() |
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask Command Execution</title> <script> function runCommand() { fetch('/') .then(response => response.text()) .then(data => { document.getElementById('output').innerText = data; }); } </script> </head> <body> <h1>Ejecutar Comando</h1> <button onclick="runCommand()">Ejecutar</button> <h2>Salida del Comando:</h2> <pre id="output"></pre> </body> </html> |

Explicación
- Hilo de fondo:
- La función
background_task
se ejecuta en un hilo separado y actualiza la variable globalthread_output
con su progreso. - Esta función se pausa por 1 segundo en cada iteración para simular trabajo.
- La función
- Rutas de Flask:
- La ruta
/
sirve una página HTML con un botón para iniciar el hilo y una área de texto para mostrar la salida del hilo. - La ruta
/start-thread
inicia el hilo si no está ya en ejecución. - La ruta
/thread-output
devuelve la salida actual del hilo y si el hilo ha terminado.
- La ruta
- JavaScript en HTML:
- La función
startThread
envía una solicitud a/start-thread
para iniciar el hilo. - La función
checkThreadOutput
envía solicitudes periódicas a/thread-output
para actualizar la salida del hilo en la página web.
- La función