flask+celery+redis异步延时处理

import time

from celery import Celery
from flask import Flask, jsonify

app = Flask(__name__)
# 配置
# 配置消息代理的路径,如果是在远程服务器上,则配置远程服务器中redis的URL
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
# 要存储 Celery 任务的状态或运行结果时就必须要配置
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
# 初始化Celery
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'], include=[app.name])
# 将Flask中的配置直接传递给Celery
celery.conf.update(app.config)


@app.route('/longtask', methods=['GET', 'POST'])
def longtask():
    task = long_task.apply_async()
    return jsonify({'task_id': task.id})


@app.route('/status/<task_id>')
def taskstatus(task_id):
    task = long_task.AsyncResult(task_id)

    if task.state == 'PENDING':
        response = {
            'state': task.state,
            'current': 0,
            'total': 100,
        }
    elif task.state != 'FAILURE':
        response = {
            'state': task.state,
            'current': task.info.get('current', 0),
            'total': task.info.get('total', 100),
        }
    else:
        response = {
            'state': task.state,
            'current': 100,
            'total': 100,
        }

    return jsonify(response)


@celery.task(name='app.long_task', bind=True)
def long_task(self):
    for i in range(100):
        self.update_state(state='PROGRESS', meta={'current': i, 'total': 100})
        time.sleep(1)

    return {'current': 100, 'total': 100}


if __name__ == "__main__":
    app.run(port=5000, debug=True)
   

执行步骤:

1.启动redis: redis-server

2.启动 celery: celery -A app.celery worker -l info -P eventlet

3.启动flask后端代码

4.浏览器启动任务得到返回任务id:http://ip:port/longtask

5.根据任务id查看任务执行进度:http://ip:port/status/任务id

猜你喜欢

转载自blog.csdn.net/qq_36940806/article/details/108522856