我正在尝试从add_contact.py
视图创建一个芹菜任务。我调用的函数位于contact_api.py
视图中。但是应用程序抛出运行时错误,表明该函数不在应用程序上下文中。但是,在tasks.py
中,该任务是在应用程序上下文中创建的。我是一个学习者,为此我感到很挣扎。
这是我的代码:
tasks.py
from celery import Celery
def make_celery(app):
celery = Celery(
app.import_name,
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
add_contact.py
import contact_api
@add_contact.route('/add_contact/<cid>', methods=['GET'])
def add_contact(cid):
name = session['name']
email = session['email']
contact_api.send_contact.delay(name, email)
return render_template('confirmation.html')
contact_api.py
@celery.task
def send_contact(name, email):
# code that calls an api
# it has some calls to the db
错误
[2018-06-25 19:52:04,016: ERROR/MainProcess] Task views.contact_api.send_contact[4d39da1f-34a7-4bac-9b8c-08b68d5d3e61] raised unexpected: RuntimeError('Working outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nto interface with the current application object in a way. To solve\nthis set up an application context with app.app_context(). See the\ndocumentation for more information.',)
我明确地尝试将with app.app_context()
设置为该方法,但是会引发相同的错误。我很困惑。请帮忙。