赞
踩
pip install celery
pip install redis
from celery import Celery
def make_celery(app):
celery = Celery(app.import_name, broker="redis://localhost:6379/0")
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
@celery.task()
def test():
with app.app_context():
your code
虽然在celery应用flask实例对象,但是如果代码里面应用到了例如flask_sqlalchemy,它也需要用到上下文。
应该注意的是,避免造成循环导包,app实例来自main.py 即from main import app
celery -A app.task.tasks:celery worker --loglevel=info
如果不加loglevel,控制台是反馈信息的
Flask-Celery-Helper 是一个flask三方库,也是配置celery的,其中就自动应用了上下文。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。