运行时错误:在应用程序上下文之外工作。烧瓶 - 邮件

Ahm*_*dir 2 python flask python-3.x flask-mail

from flask import current_app as app
from flask import render_template
from threading import Thread
from flask_mail import Message



def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['MAIL_SENDER'], recipients=[to])
    # msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=(app,msg))
    thr.start()
    return thr
    #mail.send(msg)
Run Code Online (Sandbox Code Playgroud)

运行时错误:在应用程序上下文之外工作。

这通常意味着您尝试使用需要以某种方式与当前应用程序对象交互的功能。要解决此问题,请使用 app.app_context() 设置应用程序上下文。请参阅文档以获取更多信息。

我以为我已经创建了 app_context,但代码仍然显示运行时错误。请帮忙,谢谢。

Ron*_*ino 5

您可以使用如下方式调用 async_send_mail 函数:

   app = current_app._get_current_object()
   thr = Thread(target=async_send_mail, args=[app, msg])
   thr.start()
Run Code Online (Sandbox Code Playgroud)

然后异步函数将如下所示:

def async_send_mail(app, msg):
   with app.app_context():
      mail.send(msg)
Run Code Online (Sandbox Code Playgroud)