iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python异步处理返回进度——使用Flask实现进度条
  • 527
分享到

Python异步处理返回进度——使用Flask实现进度条

2024-04-02 19:04:59 527人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录使用flask实现进度条问题描述解决方案FlaskFlask使用简单异步任务使用Flask实现进度条 问题描述 python异步处理,新起一个进程返回处理进度 解决方案 使用 t

使用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)

效果

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

接口列表

  • 执行任务: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">执行任务</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: "http://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: "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>

效果

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Python异步处理返回进度——使用Flask实现进度条

本文链接: https://www.lsjlt.com/news/117868.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python异步处理返回进度——使用Flask实现进度条
    目录使用Flask实现进度条问题描述解决方案FlaskFlask使用简单异步任务使用Flask实现进度条 问题描述 Python异步处理,新起一个进程返回处理进度 解决方案 使用 t...
    99+
    2024-04-02
  • Python中怎么使用Flask实现进度条
    本篇内容主要讲解“Python中怎么使用Flask实现进度条”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python中怎么使用Flask实现进度条”吧!使用Flask实现进度条问题描述Pyth...
    99+
    2023-06-30
  • Python显示进度条,实时显示处理进度
    发现了一个工具,tqdm,大家可以了解一下,使用tqdm就不需要自己来写代码显示进度了 在大多数时候,我们的程序会一直进行循环处理。这时候,我们非常希望能够知道程序的处理进度,由此来决定接下来该做些什么。接下来告诉大家如何简单又...
    99+
    2023-01-31
    进度 实时 进度条
  • python实现进度条
    import sysimport timedef view_bar(num, total):  rate = num / total  rate_num = int(rate * 100)  r = '\r[%s%s]%d%% ' % ("...
    99+
    2023-01-31
    进度条 python
  • Python进度条的使用
    在使用Python处理比较耗时操作的时候,为了便于观察处理进度,就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,并不是什...
    99+
    2024-04-02
  • 如何使用批处理实现进度条效果
    这篇文章主要为大家展示了“如何使用批处理实现进度条效果”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用批处理实现进度条效果”这篇文章吧。代码如下:@echo off e...
    99+
    2023-06-08
  • 使用Qt怎么实现进度条
    本篇文章为大家展示了使用Qt怎么实现进度条,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。一、前言  有时我们需要在表格(QTableWidget)、树状栏(QTreeWidget)中直观显示任务进度...
    99+
    2023-06-15
  • Python怎么实现进度条式
    这篇文章主要介绍“Python怎么实现进度条式”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python怎么实现进度条式”文章能帮助大家解决问题。Progress第一个要介绍的 Python 库是 ...
    99+
    2023-06-27
  • python进程+进度条实现赛跑效果
    利用python多进程+进度条实现一个有意思的小程序import random import time import sys from multiprocessing import ...
    99+
    2023-01-30
    进度条 进程 效果
  • C#中怎么利用异步实现一个进度条效果
    本篇文章给大家分享的是有关C#中怎么利用异步实现一个进度条效果,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。C#进度条实现之异步实例进度条页面://==============...
    99+
    2023-06-17
  • springboot利用aop实现接口异步(进度条)的全过程
    目录一、前言二、时序图三、功能演示四、关键代码ControllerAsyncAopAsyncService五、源码地址总结一、前言 在项目中发现有接口(excel导入数据)处理数据需...
    99+
    2024-04-02
  • C#使用winform实现进度条效果
    本文实例为大家分享了C#使用winform实现进度条效果的具体代码,供大家参考,具体内容如下 1.例子 2.点击查询按钮代码 private void button8_Click(...
    99+
    2024-04-02
  • 使用Ajax实现进度条的绘制
    使用:Easy Mock创建api接口 注意:若弹出该invalid or unexpected token错误提示信息,说明编写的数据格式有问题,修改为正确格式即可创建成。随后可...
    99+
    2024-04-02
  • python文本进度条怎么实现
    本篇内容介绍了“python文本进度条怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1,刚开始(可能会很low)import&nbs...
    99+
    2023-06-22
  • Python如何实现酷炫进度条
    这篇文章主要介绍了Python如何实现酷炫进度条的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python如何实现酷炫进度条文章都会有所收获,下面我们一起来看看吧。1、自定义ProgressBar最原始的办法就...
    99+
    2023-06-30
  • python实现最简单的进度条
    python实现最简单的进度条import sys,time total = 100 for i in range(total):     a = "#" * i + " " * (100-i) + "["+str(i) + "%"+"]"...
    99+
    2023-01-31
    最简单 进度条 python
  • python如何实现一个进度条
    这篇文章主要介绍python如何实现一个进度条,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!实现一个进度条from time import sleep ...
    99+
    2024-04-02
  • python如何实现普通进度条
    这篇文章将为大家详细讲解有关python如何实现普通进度条,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。普通进度条利用打印功能print进行实时刷新显示for ...
    99+
    2024-04-02
  • python 实现终端中的进度条
    # -*- coding:utf-8 -*-   # Copyright: Lustralisk # Author: test # Date: 2015-11-08   import sys, time   class ProgressBa...
    99+
    2023-01-31
    终端 进度条 python
  • python使用tqdm库实现循环打印进度条
    1. while 循环 Python的while循环可以打印进度条,可以使用tqdm这个库来实现。tqdm是一个用于在Python中添加进度条的库,它可以很容易地集成到while循环...
    99+
    2023-05-18
    python打印进度条 python循环打印
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作