Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Building the Flask App

Give Feedback

00:00 Now on to the Flask app itself. Create a new file app.py.

00:11 The responses from Google will use JSON, and the json package in the Python standard library translates between JSON objects and Python dictionaries.

00:20 The os module is used to manage environment variables. Since the client secret is a sensitive value you should not store it with the app. This app will use an environment variable instead. And sqlite3 is again needed to communicate with the database.

00:36 A number of imports are needed from flask and flask_login, but we’ll explain them in the code.

00:44 The WebApplicationClient is the class that implements the OAuth 2 flow. requests will handle HTTP traffic independent of Flask. Finally, import the method to create the database and the User class.

01:01 Retrieve the client ID and secret from environment variables and store them in constants. And one more constant for the .well-known/ endpoint to retrieve the OIDC provider configuration. At this point, you should also create a shell script to store the client ID and secret in environment variables. Create setup_env.sh

01:31 and then execute it. Back to app.py. Create a Flask app. The parameter to the Flask() initializer is the name of the application module. For a simple app, the __name__ dunder value will be fine.

01:46 Also, Flask-Login requires a secret key for encryption. Either use one stored in an environment variable or generate a new one. An instance of login_manager will add the session tracking features from Flask-Login.

02:03 Attempt to create the database. Catch a sqlite3.OperationalError in case the database already exists, in which case you should do nothing. Initialize the client with the client ID. Flask-Login depends upon a function designated as the user_loader to get a User instance given a certain user_id.

02:26 In the next lesson, you’ll define the endpoints for the app and code up the OAuth dance.

Become a Member to join the conversation.