我在使用python flask应用程序工厂应用程序实现celery时遇到问题
我打算从应用初始化文件中创建Celery应用的实例,如下所示:
from celery import Celery
celery = Celery('myapp', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0')
调用时我无法使用其他蓝图中的Celery。
答案 0 :(得分:0)
def init_celery(app):
celery = Celery()
celery.conf.broker_url = app.config['CELERY_BROKER_URL']
celery.conf.result_backend = app.config['CELERY_RESULT_BACKEND']
celery.conf.update(app.config)
class ContextTask(celery.Task):
"""Make celery tasks work with Flask app context"""
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
在create_app
时初始化芹菜:
init_celery(app)
了解如何在this Flask cookiecutter中实现芹菜
答案 1 :(得分:0)
来自@API的答案是正确的...还将以下内容添加到您的celery配置中...这将有助于防止在代理关闭或无法访问时由celery引起的无休止的重试。.
broker_transport_options = {
'max_retries': 3,
'interval_start': 0,
'interval_step': 0.2,
'interval_max': 0.5,
}
在回答此问题时,所用芹菜的版本为== 4.3。
答案 2 :(得分:0)
JoostDöbken的答案可能有用,但似乎比必须要复杂一些。
我找到了Miguel Grinberg的简单解决方案,对我来说非常有用:
from celery import Celery
from config import config, Config
celery = Celery(__name__, broker=Config.CELERY_BROKER_URL)
def create_app(config_name):
# ...
celery.conf.update(app.config)
# ...
return app
https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern