from google_auth_oauthlib.flow import InstalledAppFlow # Create flow from client secrets file flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', scopes=['email', 'calendar']) # Start the OAuth flow for authorization creds = flow.run_local_server(port=0) # Store the credentials for future use # (e.g. when making API requests) creds.to_json()
from google_auth_oauthlib.flow import InstalledAppFlow # Create flow from client secrets file flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', scopes=['email', 'calendar']) # Try to load the stored credentials creds = None try: creds = flow.credentials except Exception as e: # CredentialsNotFound, FileNotFoundError print(f'Error loading credentials: {e}') # If no stored credentials, start the OAuth flow for authorization if not creds or not creds.valid: creds = flow.run_local_server(port=0) # Store the credentials for future use creds.to_json()In this example, we first try to load the user's stored credentials from a previous OAuth flow. If the credentials are missing or invalid, we start a new OAuth flow by calling `run_local_server`. We then store the user's credentials for future use. Overall, `InstalledAppFlow` with `from_client_secrets_file` is a powerful and flexible way to authenticate with Google APIs in Python.