Flask-Mail breaks Celery

强颜欢笑 提交于 2019-12-06 11:45:24

Update

The bug is in the render_template portion of the send_email task.

@celery.task
def send_email(some_arg, name, email):
    msg = Message(
                  subject='hello', 
                  body=render_template('email.txt',
                  name=name, 
                  some_arg=some_arg),
                  recipients=[email]
                 )
    return mail.send(msg)

When I remove body=render_template, kablaam, it works.

I've got from flask import render_template. Perhaps render_template can't work like this?

Strangely, without Celery, the send_email plus render_template works perfect.

Hackish Success

When I force the app_context with another function everything works:

def create_email(some_arg, name, email):
    with app.test_request_context('/send_email'):
        return render_template('email.txt', 
                                name=name, 
                                some_arg=some_arg) 

and then toss it in the send_email task so

body = render_template('email.txt'…

becomes

body= create_email(some_arg, name)

And we're home free.

A lot of things done in flask are bound to the application context. For example, the render_template function, it needs to know where your application stores its templates. The session variable wants to know your application's data store or caching system. The request object, and your mail.send require some application context when being called.

If you want to call them outside the scope of your flask application, like in your celery task, do it within the app context like so:

...

with app.app_context():

    do_some_context_bound_actions()

    msg = Messgae(...)
    user_name = app.session["user"].name
    msg.html = render_template("mail/welcome.html", name=user_name)
    mail.send(msg)

...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!