溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中怎么使用Flask實現(xiàn)進度條

發(fā)布時間:2022-05-11 10:22:58 來源:億速云 閱讀:536 作者:iii 欄目:開發(fā)技術

本篇內(nèi)容主要講解“Python中怎么使用Flask實現(xiàn)進度條”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Python中怎么使用Flask實現(xiàn)進度條”吧!

    使用Flask實現(xiàn)進度條

    問題描述

    Python異步處理,新起一個進程返回處理進度

    解決方案

    使用 tqdm 和 multiprocessing.Pool

    安裝

    pip install tqdm

    代碼

    import time
    import threading
    from multiprocessing import Pool
    from tqdm import tqdm
    def do_work(x):
        time.sleep(x)
        return x
    def progress():
        time.sleep(3)  # 3秒后查進度
        print(f'任務有: {pbar.total} 已完成:{pbar.n}')
    tasks = range(10)
    pbar = tqdm(total=len(tasks))
    if __name__ == '__main__':
        thread = threading.Thread(target=progress)
        thread.start()
        results = []
        with Pool(processes=5) as pool:
            for result in pool.imap_unordered(do_work, tasks):
                results.append(result)
                pbar.update(1)
        print(results)

    效果

    Python中怎么使用Flask實現(xiàn)進度條

    Flask

    安裝

    pip install flask

    main.py

    import time
    from multiprocessing import Pool
    from tqdm import tqdm
    from flask import Flask, make_response, jsonify
    app = Flask(__name__)
    def do_work(x):
        time.sleep(x)
        return x
    total = 5  # 總?cè)蝿諗?shù)
    tasks = range(total)
    pbar = tqdm(total=len(tasks))
    @app.route('/run/')
    def run():
        """執(zhí)行任務"""
        results = []
        with Pool(processes=2) as pool:
            for _result in pool.imap_unordered(do_work, tasks):
                results.append(_result)
                if pbar.n >= total:
                    pbar.n = 0  # 重置
                pbar.update(1)
        response = make_response(jsonify(dict(results=results)))
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', '*')
        response.headers.add('Access-Control-Allow-Methods', '*')
        return response
    @app.route('/progress/')
    def progress():
        """查看進度"""
        response = make_response(jsonify(dict(n=pbar.n, total=pbar.total)))
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', '*')
        response.headers.add('Access-Control-Allow-Methods', '*')
        return response

    啟動(以 Windows 為例)

    set FLASK_APP=main
    flask run

    接口列表

    • 執(zhí)行任務:http://127.0.0.1:5000/run/

    • 查看進度:http://127.0.0.1:5000/progress/

    test.html

    <!DOCTYPE html>
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <title>進度條</title>
        <script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
        <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow"  rel="stylesheet">
    </head>
    <body>
    <button id="run">執(zhí)行任務</button>
    <br><br>
    <div class="progress">
        <div class="progress-bar" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100"
             >0.00%
        </div>
    </div>
    </body>
    <script>
        function set_progress_rate(n, total) {
            //設置進度
            var rate = (n / total * 100).toFixed(2);
            if (n > 0) {
                $(".progress-bar").attr("aria-valuenow", n);
                $(".progress-bar").attr("aria-valuemax", total);
                $(".progress-bar").text(rate + "%");
                $(".progress-bar").css("width", rate + "%");
            }
        }
        $("#run").click(function () {
            //執(zhí)行任務
            $.ajax({
                url: "http://127.0.0.1:5000/run/",
                type: "GET",
                success: function (response) {
                    set_progress_rate(100, 100);
                    console.log('執(zhí)行完成,結(jié)果為:' + response['results']);
                }
            });
        });
        setInterval(function () {
            //每1秒請求一次進度
            $.ajax({
                url: "http://127.0.0.1:5000/progress/",
                type: "GET",
                success: function (response) {
                    console.log(response);
                    var n = response["n"];
                    var total = response["total"];
                    set_progress_rate(n, total);
                }
            });
        }, 1000);
    </script>
    </html>

    效果

    Python中怎么使用Flask實現(xiàn)進度條

    Flask使用簡單異步任務

    在Flask中使用簡單異步任務最簡潔優(yōu)雅的原生實現(xiàn):

    from flask import Flask
    from time import sleep
    from concurrent.futures import ThreadPoolExecutor
    # DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
    executor = ThreadPoolExecutor(2)
    app = Flask(__name__)
    @app.route('/jobs')
    def run_jobs():
        executor.submit(some_long_task1)
        executor.submit(some_long_task2, 'hello', 123)
        return 'Two jobs was launched in background!'
    def some_long_task1():
        print("Task #1 started!")
        sleep(10)
        print("Task #1 is done!")
    def some_long_task2(arg1, arg2):
        print("Task #2 started with args: %s %s!" % (arg1, arg2))
        sleep(5)
        print("Task #2 is done!")
    if __name__ == '__main__':
        app.run()

    到此,相信大家對“Python中怎么使用Flask實現(xiàn)進度條”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

    AI