| 123456789101112131415161718192021222324252627282930313233343536 |
- from google_auth_oauthlib.flow import InstalledAppFlow
- from google.auth.transport.requests import Request
- import os
- import pickle
- # OAuth 2.0 scopes
- SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
- def get_token():
- """Perform OAuth authentication and save the token."""
- creds = None
- # The token file to save credentials
- token_file = "youtube_token.pickle"
- # Check if token file exists
- if os.path.exists(token_file):
- with open(token_file, "rb") as token:
- creds = pickle.load(token)
- # If no valid credentials, authenticate user
- if not creds or not creds.valid:
- if creds and creds.expired and creds.refresh_token:
- creds.refresh(Request())
- else:
- flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", SCOPES)
- creds = flow.run_local_server(port=0)
- # Save the credentials to a file
- with open(token_file, "wb") as token:
- pickle.dump(creds, token)
- print(f"Token saved to {token_file}")
- else:
- print("Token already exists and is valid.")
- if __name__ == "__main__":
- get_token()
|