Xử lý tiến trình với Flask và Threading

admin

Ròm Tiến Đạt
Automation
Mã:
from flask import Flask, jsonify
import time
import threading

app = Flask(__name__)

@app.route('/')
def home():
    # Trang HTML chính
    return '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Live Updates</title>
        <script>
            function fetchUpdates() {
                fetch('/progress')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('dynamic-content').innerText = data.progress;
                });
            }
            setInterval(fetchUpdates, 1000); // Gọi API mỗi giây
        </script>
    </head>
    <body>
        <h1>Live Updates</h1>
        <div id="dynamic-content">Đang tải...</div>
    </body>
    </html>
    '''

@app.route('/update')
def update():
    # API trả về dữ liệu động
    current_time = time.strftime('%H:%M:%S')  # Lấy thời gian hiện tại
    return jsonify(message=f"Thời gian hiện tại: {current_time}")

# Khởi tạo trạng thái tiến trình
total = 100  # Tổng số phần tử cần xử lý
current = 0  # Bắt đầu từ phần tử đầu tiên
completed = False  # Trạng thái hoàn thành

@app.route('/progress')
def progress():
    # API trả về trạng thái tiến trình với ví dụ vòng lặp

    def process_task():
        global current, completed
        for i in range(current, total + 1):
            time.sleep(1)  # Giả lập xử lý mất 1 giây
            current = i
        completed = True  # Đánh dấu hoàn thành khi xử lý xong

    # Chạy tiến trình trong một luồng riêng
    if current == 0 and not completed:
        threading.Thread(target=process_task, daemon=True).start()

    if completed:
        return jsonify(progress="Hoàn thành!")
    else:
        return jsonify(progress=f"Đang xử lý: {current}/{total}")

if __name__ == '__main__':
    app.run()
 
Bên trên