Running Celery worker inside an app context still raises “working outside of app context” error in task

拈花ヽ惹草 提交于 2019-12-05 08:57:53

I was able to fix the issue by creating an instance of the flask application locally:

email.py:

from flask import render_template, current_app
from flask.ext.mail import Message
from . import celery, mail, create_app


@celery.task
def send_async_email(msg):
    app = create_app('default' or 'development')  # -> fixed
    with app.app_context():
        mail.send(msg)


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(current_app.config['PORTAL_MAIL_SUBJECT_PREFIX'] + ' ' +     subject,
    sender=current_app.config['MAIL_USERNAME'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    send_async_email.delay(msg)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!