Flask教程(二十三)简单异步任务
source link: https://xugaoxiang.com/2020/11/16/flask-23-threadpoolexecutor/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
软硬件环境
视频看这里
此处是youtube
的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。
从Python
3.2开始,标准库为我们提供了concurrent.futures
模块,它提供了ThreadPoolExecutor
(线程池)和ProcessPoolExecutor
(进程池)两个类。使用submit
方法来提交线程(或进程)需要执行的任务到线程(进程)池中,并返回该任务的句柄,submit
不是阻塞的,而是立即返回。通过任务句柄的done()
方法来判断该任务是否结束,通过result()
方法可以获取任务的返回值。
结合concurrent.futures
模块,可以在flask
应用中实现简单异步任务。
直接来看代码吧
from flask import Flask
import time
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(2)
app = Flask(__name__)
@app.route('/tasks')
def run_background_tasks():
# 提交2个任务,一个带参、一个不带参
executor.submit(background_task1)
executor.submit(background_task2, 'hello', 'future')
return 'tasks started in background!'
def background_task1():
print("background_task1 started!")
time.sleep(10)
print("background_task1 done!")
def background_task2(arg1, arg2):
print(f"background_task2 started with args: {arg1} {arg2}!")
time.sleep(5)
print("background_task2 done!")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
启动flask
服务后,访问http://127.0.0.1:5000/tasks
,观察终端的打印输出
https://github.com/xugaoxiang/FlaskTutorial
Flask教程专题
更多Flask
教程,请移步
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK