In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use Flask to achieve the progress bar in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use Flask in Python to achieve progress bar"!
Using Flask to implement the problem description of progress bar
Python asynchronous processing, and a new process returns the processing progress
Solution
Using tqdm and multiprocessing.Pool
Installation
Pip install tqdm
Code
Import timeimport threadingfrom multiprocessing import Poolfrom tqdm import tqdmdef do_work (x): time.sleep (x) return xdef progress (): time.sleep (3) # check the progress print (f 'task: {pbar.total} completed: {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)
Effect.
Flask
Installation
Pip install flask
Main.py
Import timefrom multiprocessing import Poolfrom tqdm import tqdmfrom flask import Flask, make_response, jsonifyapp = Flask (_ _ name__) def do_work (x): time.sleep (x) return xtotal = 5 # Total tasks tasks = range (total) pbar = tqdm (total=len (tasks)) @ app.route ('/ run/') def run (): "" execute tasks "" 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 # reset 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 (): "View 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
Start (take Windows as an example)
Set FLASK_APP=mainflask run
Interface list
Perform Task: http://127.0.0.1:5000/run/
Check progress: http://127.0.0.1:5000/progress/
Test.html
Progress bar executes tasks
0.005% function set_progress_rate (n, total) {/ / set progress 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 () {/ / execute task $.ajax ({url: "http://127.0.0.1:5000/run/", type:" GET ", success: function (response) {set_progress_rate (100,100) Console.log ('execution completed, the result is:' + response ['results']);});}) SetInterval (function () {/ / request progress $.ajax every second ({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)
Effect.
Flask uses simple asynchronous tasks
Use the most concise and elegant native implementation of simple asynchronous tasks in Flask:
From flask import Flaskfrom time import sleepfrom concurrent.futures import ThreadPoolExecutor# DOCS https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutorexecutor = 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 backgroundconstrucdef 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 () so far, I believe you have a better understanding of "how to use Flask to implement the progress bar in Python" You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.