大蟒蛇python教程共享Python异步处理返回进度——使用Flask实现进度条

使用flask实现进度条

问题描述

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实现进度条

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  # 总任务数  tasks = range(total)  pbar = tqdm(total=len(tasks))  @app.route('/run/')  def run():      """执行任务"""      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

接口列表

  • 执行任务:https://127.0.0.1:5000/run/
  • 查看进度:https://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">执行任务</button>  <br><br>  <div class="progress">      <div class="progress-bar" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100"           style="width: 10%">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 () {          //执行任务          $.ajax({              url: "https://127.0.0.1:5000/run/",              type: "get",              success: function (response) {                  set_progress_rate(100, 100);                  console.log('执行完成,结果为:' + response['results']);              }          });      });      setinterval(function () {          //每1秒请求一次进度          $.ajax({              url: "https://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实现进度条

flask使用简单异步任务

在flask中使用简单异步任务最简洁优雅的原生实现:

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()

以上为个人经验,希望能给大家一个参考,也希望大家多多支持<计算机技术网(www.ctvol.com)!!>。

需要了解更多python教程分享Python异步处理返回进度——使用Flask实现进度条,都可以关注python教程分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/pythontutorial/1091604.html

(0)
上一篇 2022年5月11日
下一篇 2022年5月11日

精彩推荐