python - 运行时错误 : Working outside of application context. Flask - 邮件

标签 python python-3.x flask 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)

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

这通常意味着您尝试使用所需的功能 以某种方式与当前应用程序对象交互。解决 为此,使用 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/

相关文章:

Python bz2 - 文本与交互式控制台(数据流)

python - 使用 Python 将两个 CSV 文件与案例合并

python - 保存到外部 PY 文件?

python - 在跳过第一行并使用第二行作为 pandas 中符号的原始刻度数据的标题时,无法读取 csv

python-3.x - 使用 Imblearn 管道和 GridSearchCV 进行交叉验证

python - 使用 Flask-SQLAlchemy 选择多对多

python - 打印在 __getattr__ 中不起作用

python - 一个数字在 numpy 数组中出现了多少次

jquery - WTForms 与 Jquery Form Plugin 耦合时如何显示验证错误?

python - 围绕现有数据库的 Flask sqlalchemy 示例