Accessing an object through views in Flask without instantiating for every request

I am trying to make an external API call that authenticates a user on some domain and returns an object B

. This object B

needs to be available for multiple view functions, but I don't want to create it every request in before_request

or store authentication information in a session or database because it is sensitive.

Based on this SO post I thought I could use an object g

, but I get AttributeError: '_AppCtxGlobals' object has no attribute 'B'

when I try to access the object in another function.

The only thing that has worked so far is initialize B

as a global variable, but that doesn't seem like good practice or safety.

How can I create and save this object so that it is available for multiple view functions?

@app.route('/login', methods=['GET', 'POST'])
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm()

    if form.validate_on_submit():
        email = form.email.data
        pw = form.password.data
        g.B = Bindings(domain='somewebsite.com', user=email, auth=pw)

    return render_template('login.html', form=form)

@app.route('/devices')
def devices():
    devices = g.B.get_all_devices()
    return render_template('home/devices.html', devices=devices)

      

+3


source to share





All Articles