Access to a protected member _get_current_object of a class
引用send_mail方法的第一行
app = current_app._get_current_object()
用来编码语句的更合适的方法是什么?
from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from . import mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=app.config['FLASKY_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
Current_App是您的Blask App实例
的。它具有您的应用程序上下文。您无需从Current_App类访问受保护的成员。只需将其作为应用程序导入或以app的速度将其作为应用程序,然后执行您的操作即可。例如:# Importing and aliasing current_app
from flask import current_app as app
# this is perfectly fine
sender = app.config['FLASKY_MAIL_SENDER']
您不应从库或框架中访问受保护的成员。仅使用公共API暴露的成员,或冒着在以后的库更新中破坏代码的风险。
I在信号部分中找到了使用此函数的原因:https://flask.palletsprojects.com/en/stable/signals/#:〜:text = text = taster%20proxies%20AS%20AS%20senders