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)
运行时错误:在应用程序上下文之外工作。
这通常意味着您尝试使用所需的功能 以某种方式与当前应用程序对象交互。解决 为此,使用 app.app_context() 设置应用程序上下文。请参阅 文档以获取更多信息。
我以为我已经创建了app_context,但代码仍然显示运行时错误。请帮忙,谢谢。
最佳答案
您可以使用如下方式调用 async_send_mail 函数:
app = current_app._get_current_object()
thr = Thread(target=async_send_mail, args=[app, msg])
thr.start()
然后异步函数将如下所示:
def async_send_mail(app, msg):
with app.app_context():
mail.send(msg)
关于python - 运行时错误 : Working outside of application context. Flask - 邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63951187/