【问题标题】:RuntimeError: Working outside of application context. Flask - MailRuntimeError:在应用程序上下文之外工作。烧瓶 - 邮件
【发布时间】:2020-09-18 07:33:38
【问题描述】:
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)

RuntimeError:在应用程序上下文之外工作。

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

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

【问题讨论】:

    标签: python python-3.x flask flask-mail


    【解决方案1】:
    app = current_app._get_current_object()
    with app.app_context():
        pass
        # send email here
    

    from main import app
    with app.app_context():
        pass
    
    # main.py
    app = Flask(__name__)
    

    _get_current_object():

    返回当前对象。如果出于性能原因或因为您想将对象传递到不同的上下文中,您希望一次将真实对象放在代理后面,这将非常有用。

    current_app 是一个 Flask 代理对象:

    current_app = LocalProxy(_find_app)
    

    你只能在当前线程中从 current_app 获取 app 对象

    【讨论】:

    • 仍然显示错误,main 是一个蓝图,应用程序没有从中导入 ImportError: cannot import name 'app' from 'app.main' (C:\Users\USER\Documents\Global\voting2\app\main\__init__.py)
    【解决方案2】:

    你可以这样调用 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)
    

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 2012-10-29
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多