当前位置: 代码迷 >> 综合 >> 骚气的Python之Celery
  详细解决方案

骚气的Python之Celery

热度:53   发布时间:2024-01-20 03:49:53.0

在我的__init__.py  文件里配置,需要先安装redis,mac上安装: brew install redis

from celery import Celery#初始化Flask对象
app = Flask(__name__)app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/1'celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

 然后在 tasks.py 写个任务

from __init__ import celery
import time
@celery.task
def add(x,y):for i in range(10):time.sleep(1)print(i)# print("%s + %s = " % (x, y) )return x + y

接着在路由调用tasks,后台会在celery进程里运行 add 任务,而 flask 进程不受影响直接返回 “bbb”,而如果去使用 task.get()会等待add任务结束才会返回“bbb”

from tasks import add
@app.route('/mytest', methods=['GET'])  # 登录校验
# @auth_check
def mytest():print("mytest")task =add.delay(2, 4)# print(task.get())return "bbb"

 

 celery需要在控制台独立启动

celery worker -A __init__.celery --loglevel=info

 

 

  相关解决方案