Flask:更新的代码参考:current_app_get_current_object()



我正在一起学习Python和Flask。我正在将一个代码示例更新到最新的Flask版本(2.2.2(,PyCharm报告了以下警告:

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是Flask应用程序实例的代理。它有你的应用程序的上下文。您不需要从current_app类访问受保护的成员。只需将其导入为应用程序或稍后将其别名为应用程序即可执行操作。例如:

# Importing and aliasing current_app
from flask import current_app as app
# this is perfectly fine
sender = app.config['FLASKY_MAIL_SENDER']

您不应该从库或框架访问受保护的成员。仅使用公共API公开的成员,否则在将来的库更新中可能会破坏代码。

最新更新