AttributeError: Object "NoneType" has no attribute "application" when trying to send mail in Flask

I am following the flask tutorial to practice flash mail, but I am running into something that seems like a bug. I don’t understand what happened?

This is my code:

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)

      

This is the error information:

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'

      

+3


source to share


1 answer


When I call with app.app_context():

I solved my problem.



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)

      

+5


source







All Articles