Skip to content

Instantly share code, notes, and snippets.

@CoreyMSchafer
Created September 10, 2020 02:06
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save CoreyMSchafer/ea5e3129b81f47c7c38eb9c2e6ddcad7 to your computer and use it in GitHub Desktop.
Save CoreyMSchafer/ea5e3129b81f47c7c38eb9c2e6ddcad7 to your computer and use it in GitHub Desktop.
YouTube-OAuth-Snippets
# token.pickle stores the user's credentials from previously successful logins
if os.path.exists('token.pickle'):
print('Loading Credentials From File...')
with open('token.pickle', 'rb') as token:
credentials = pickle.load(token)
# Google's Request
from google.auth.transport.requests import Request
# If there are no valid credentials available, then either refresh the token or log in.
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
print('Refreshing Access Token...')
credentials.refresh(Request())
else:
print('Fetching New Tokens...')
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json',
scopes=[
'https://www.googleapis.com/auth/youtube.readonly'
]
)
flow.run_local_server(port=8080, prompt='consent',
authorization_prompt_message='')
credentials = flow.credentials
# Save the credentials for the next run
with open('token.pickle', 'wb') as f:
print('Saving Credentials for Future Use...')
pickle.dump(credentials, f)
@wbijster
Copy link

Many thanks for your video and these snippets!

Just 1 question: why do you not save the credentials after a refresh?

@techtribeyt
Copy link

^ also wondering this

@crowellel
Copy link

Hi! Really grateful for this snippet, but confused about lines 13 & 14:
How is "credentials.valid" and "credentials.expired" determined? I've looked through the imports and can't find anything referencing "credentials.valid" or "credentials.expired".
Anyway, thanks for this snippet!

@Kamalabot
Copy link

The saving credentials is a huge time saver. thanks for sharing the logic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment