Posts tagged with flask

I am trying to integrate Oauth2 into my Flask application, and am having some issues with keeping the flow persistent despite a redirect.

def account(): form = UpdateAccountForm() authorization_url = '' auth_code = request.args.get('code') if request.method == 'POST':     if request.form['submit_button'] == 'Test':         flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',      scopes=['https://www.googleapis.com/auth'])         flow.redirect_uri = 'http://127.0.0.1:5000/account'         authorization_url, state = flow.authorization_url(access_type='offline',                  prompt='consent', include_granted_scopes='true')         print('Please go to this URL: {}'.format(authorization_url)) if auth_code != None:     flow.fetch_token(code=auth_code)     credentials = flow.credentials     print(credentials) 

Upon button click, the Oauth flow is initiated and the user is presented with a link to a Google page in which they grant my application access to some of their features. Then, the user is redirected back to the same page but with an authorization code attached to the request which is fed back into the flow and allows me to gain access the users credentials.

This part:

if auth_code != None:     flow.fetch_token(code=auth_code)     credentials = flow.credentials     print(credentials) 

When the page reloads I get:

UnboundLocalError: local variable 'flow' referenced before assignment

I assume this happens because the flow is no longer initialized when the page loads, and obviously I can't initialize a new flow the next time the page loads because the object would be different.

I am not sure how to approach this problem within Flask, what would be the best way to keep the flow consistent?

EDIT: This question is different from the suggested duplicate because this uses Oauthlibs Flow module as opposed to the previously suggested. The closest answer is here: https://developers.google.com/identity/protocols/OAuth2WebServer but still inadequate.