【发布时间】:2016-10-23 05:37:09
【问题描述】:
我有一个Flask应用,注册如下:
APP = Flask(__name__)
APP.config.from_object('config')
我为 URL 定义了一个视图,其中调用了一个与 DB 交互的函数。
from tasks import some_func
.
.
.
some_func.delay(params)
在tasks.py文件中,我创建一个Celery实例如下:
# Config values don't work here
celery = Celery('tasks', broker='amqp://', backend='amqp://')
.
.
.
@celery.task()
def some_func():
#DB interactions
现在我收到一条错误消息:
RuntimeError: Working outside of application context.
我阅读了有关应用程序上下文以及如何使用它们的信息。我在tasks.py 文件中导入了current_app,并尝试使用如下上下文:
@celery.task()
def some_func():
with current_app.app_context():
#DB interactions
但是我仍然遇到同样的错误。我还尝试从主文件中推送上下文,如下所示:
ctx = APP.app_context()
ctx.push()
但还没有运气。
如何让 Celery 与 Flask 一起工作?
注意:我已经尝试过他们的example here。
【问题讨论】:
-
task.py中的视图有导入吗?如果你有一个,循环导入可能是个问题。事实上,您有数据库交互,并且可能数据库实例使用您的应用程序。
-
@Nonnib 我已经尝试过这个和许多类似的解决方案,但 Celery 似乎仍在抱怨。
-
@Hamlett 不。主文件导入所有内容以将其绑定在一起。任务文件导入执行处理的其他文件。
-
您找到解决方案了吗?
标签: python flask celery message-queue task-queue