【问题标题】:Flask integration with CeleryFlask 与 Celery 的集成
【发布时间】:2015-02-12 16:51:13
【问题描述】:

我正在尝试在我的Flask Example application 中使用 Celery。因为我在工厂方法中创建实例,所以我不能使用文档中的示例 (http://flask.pocoo.org/docs/0.10/patterns/celery/)

init.py

from celery import Celery
from flask import Flask
from config import config


def create_app():
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(config)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)


    return app

def make_celery(app = None):
    app = app or create_app()
    celery = Celery('app', backend=app.config['CELERY_RESULT_BACKEND'], broker=app.config['CELERY_BROKER_URL'])
    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

tasks.py

from app import make_celery

celery = make_celery()


@celery.task
def add(a, b):
    return a + b

views.py

from flask import render_template
from app.main import main
from ..tasks import add

@main.route('/', methods=['GET', 'POST'])
def index():
    add.delay(5, 3)
    return render_template('index.html')

我收到了error

$  celery -A app.tasks worker
回溯(最近一次通话最后): 文件“...lib/python3.4/site-packages/celery/app/utils.py”,第 229 行,在 find_app sym = symbol_by_name(app, imp=imp) 文件“...lib/python3.4/site-packages/celery/bin/base.py”,第 488 行,在 symbol_by_name 中 return symbol_by_name(name, imp=imp) 文件“...lib/python3.4/site-packages/kombu/utils/__init__.py”,第 97 行,在 symbol_by_name 中 返回 getattr(module, cls_name) if cls_name else module AttributeError:“模块”对象没有属性“任务”

【问题讨论】:

  • 您没有名为app.py 的文件,因此tasks.py 无法从中导入。你的意思是from . import make_celery

标签: flask celery python-3.4


【解决方案1】:

-A 参数应该指向要使用的 Celery 实例,而不是模块 http://docs.celeryproject.org/en/latest/reference/celery.bin.celery.html#cmdoption-celery-a

在这种情况下:

celery -A app.tasks.celery worker

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 2015-05-18
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多