AttributeError: 'NoneType' object has no attribute 'app' when trying to send mail in Flask

AttributeError: 'NoneType' object has no attribute 'app' when trying to send mail in Flask

我正在按照 flask 教程练习做 flask-mail 但我遇到了一些似乎是错误的东西。我不明白发生了什么?

这是我的代码:

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    mail.send(msg)

这是错误信息:

Traceback (most recent call last):
  File "ch6_1.py", line 64, in <module>
    send_email(app ,MAIL_USERNAME, "test mail", "hello")
  File "ch6_1.py", line 50, in send_email
    msg.body = render_template(template + '.txt', **kwargs)
  File "D:\INSTALL\Python\lib\site-packages\flask\templating.py", line 126, in r
ender_template
    ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'

当我调用with app.app_context():时,我的问题就解决了。

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    with app.app_context():
        msg.body = render_template(template + '.txt', **kwargs)
        msg.html = render_template(template + '.html', **kwargs)
        mail.send(msg)