运行 来自 FLASK 应用的 Celery Worker

Run Celery Worker from FLASK app

我正在 FLASK 中制作一个应用程序,并将 Celery 合并到其中。但是,如果我想让 Celery worker 也能正常工作,我必须通过终端 运行 应用程序。 (celery -A app.celery worker)。我尝试 运行 从主 run.py 文件中将其

init.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from celery import Celery
from kombu import serialization


app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
mail = Mail(app)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
app.config['CELERY_ACCEPT_CONTENT'] = ['json']
app.config['CELERY_TASK_SERIALIZER'] = 'json'
app.config['CELERY_RESULT_SERIALIZER'] = 'json'
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
serialization.registry._decoders.pop("application/x-python-serialize")

from app import views

和run.py

#!flask/bin/python
from __future__ import absolute_import, unicode_literals
from app import app
# app.run(debug=True, port=9001)

from celery import current_app    
from celery.bin import worker

app = current_app._get_current_object()

worker = worker.worker(app=app)

options = {
    'broker': app.config['CELERY_BROKER_URL'],
    'loglevel': 'INFO',
    'traceback': True,
}

worker.run(**options)

但这给出了错误 AttributeError: 'Celery' object has no attribute 'config'

任何关于我做错了什么的指示将不胜感激。

您的 run.py 应该是:

#!flask/bin/python
from __future__ import absolute_import, unicode_literals
from app import app
# app.run(debug=True, port=9001)

from celery import current_app    
from celery.bin import worker

application = current_app._get_current_object()

worker = worker.worker(app=application)

options = {
    'broker': app.config['CELERY_BROKER_URL'],
    'loglevel': 'INFO',
    'traceback': True,
}

worker.run(**options)