python - RuntimeError:在应用程序上下文之外工作。烧瓶 - 邮件
问题描述
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,但代码仍然显示运行时错误。请帮忙,谢谢。
解决方案
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 获取应用程序对象
推荐阅读
- azure - “this.Client.SubscriptionId”不能为空
- regex - 如何使用powershell编写正则表达式以仅替换tnsnames.ora中的HOST名称
- c++ - 使用 thread_local 维护并发内存缓冲区时发生错误
- reactjs - 无法从父组件调用子组件的函数。错误:“...不是函数”
- floating-point - 给定一个浮点算术表达式,如何确保其舍入结果大于真实结果?
- mysql - 无法创建或更改没有主键的表 - Laravel DigitalOcean 托管数据库
- ios - 如何在异步回调中访问函数参数?
- adobe-xd - 如何从 Adobe Xd 导出颜色资源?
- python - 无法将输入数组从形状 (27839,1) 广播到形状 (27839)
- javascript - Moment js 有没有办法为所有时区设置相同的时间?