Home > Back-end >  Flask: Update Code Reference for: current_app._get_current_object()
Flask: Update Code Reference for: current_app._get_current_object()

Time:08-29

I'm learning Python and Flask together. I'm updating a code example to the latest Flask version (2.2.2) and PyCharm is reporting the following warning:

Access to a protected member _get_current_object of a class

in reference to the first line of the send_mail method

app = current_app._get_current_object()

What is a more appropriate way to code the statement?

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

CodePudding user response:

current_app is a proxy to your Flask app instance. It has your application's context. You don't need to access protected members from current_app class. Simply import it as app or alias it as app later on and perform your operations. For example:

# Importing and aliasing current_app
from flask import current_app as app

# this is perfectly fine
sender = app.config['FLASKY_MAIL_SENDER']

You shouldn't access protected members from a library or a framework. Only use members exposed by public API, or risk breaking your code in a future library update.

  • Related