pythonflaskauthlibflask-oauthlib

How can I use oauth.create_client in different file than the one I called the constructor, in Authlib?


I need to connect to a website using Authlib. I am a newbie at this, so I studied some tutorials: one., two, three All of them gave the following structure:

  1. create the app instance;
  2. create the oauth instance, passing app to the OAuth constructor;
  3. using oauth in the routing function decorators.

This structure is in the same file. The problem is that I need to use the oauth instance in a different file than the one the instance (point 3 from above) was created and I don't know how to do it. Some help is more than necessary.

Useful code:

__init__py:

from authlib.integrations.flask_client import OAuth
app = Flask(__name__, template_folder="templates", static_folder="static")
app.config.from_object('config.Config')
oauth = OAuth(app)
oauth.register(name='Hattrick', client_id='...',
                       client_secret='...',
                       request_token_url='...',
                       request_token_params=None,
                       access_token_url='...',
                       access_token_params=None,
                       authorize_url='...', authorize_params=None,
                       api_base_url='...', client_kwargs=None)

/index/index_routes.py

@index_bp.route('/LoginToHattrick')
def LoginToHattrick():
    hattrick = oauth.create_client('Hattrick')
    return hattrick.authorize_redirect('...')

Solution

  • Move the oauth definition to index routes:

    @index_bp.route('/LoginToHattrick')
    def LoginToHattrick():
        oauth = OAuth(wsgi.app)
        oauth.register(name='Hattrick', client_id='...',
                           client_secret='...',
                           request_token_url='...',
                           request_token_params=None,
                           access_token_url='...',
                           access_token_params=None,
                           authorize_url='...', authorize_params=None,
                           api_base_url='...', client_kwargs=None)
        hattrick = oauth.create_client('Hattrick')
        return hattrick.authorize_redirect('...')