码迷,mamicode.com
首页 > 编程语言 > 详细

python使用flask+Thread实现异步任务

时间:2020-03-08 20:13:10      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:行业   art   www   print   sync   使用   port   sel   inf   

# 定义一个WorkerController,用于执行业务代码
class WorkerController(object):

    def __init__(self):
        pass

    def do_something(self, params):
        print("do something")
# 定义一个AsyncWorker,继承Thread,重写run方法,run方法中调用WorkerController的do_something方法

from threading import Thread
from worker_controller import WorkerController

WORKER_CONTROLLER = WorkerController()


class AsyncWorker(Thread):
    ASYNC_WORKER_INFO = dict()

    def __init__(self, params, ticket_id):
        Thread.__init__(self)
        self.params = params
        self.ticket_id = ticket_id
        self.daemon = True
        self.start()

    def run(self):
        AsyncWorker.ASYNC_WORKER_INFO[self.ticket_id] = {
            # 保存一些业务信息,之后轮询的时候,可以作为输出返回
            "some": "information",
            "status": "running"
        }
        WORKER_CONTROLLER.do_something(self.params)
# 开始任务
@app.route('/do-something', methods=['GET'])
def do_something():
    params = request.args.get('params', '').strip()
    # 生成一个任务id,用于轮询,例如ticket id
    ticket_id = genearteMD5(str(int(round(time.time() * 1000))))
    # 实例化一个AsyncWorker
    AsyncWorker(params=params, ticket_id=ticket_id)
    # 将ticket_id返回
    return jsonify({"ticket_id": ticket_id})

# 轮询任务
@app.route("/check-status", methods=['GET'])
def check_status():
    ticket_id = request.args.get("ticket_id")
    logs = AsyncWorker.ASYNC_WORKER_INFO[str(ticket_id)]
    return jsonify(logs)

如何在前端进行异步轮询呢?以angularjs的interval方法为例:https://www.cnblogs.com/CheeseZH/p/12444034.html

python使用flask+Thread实现异步任务

标签:行业   art   www   print   sync   使用   port   sel   inf   

原文地址:https://www.cnblogs.com/CheeseZH/p/12444086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!