I have 2 yotube api projects, I want my code to switch between the 2 (token.pickle) files when the quota exceeded error occurs.
Below is what I have tried:
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']# List of client secret files for different projectsclient_secret_files = ['client_secret.json', 'client_secret2.json']# Holds active tokenstokens = []current_token_index = 0def load_tokens():"""Load tokens for each client secret file or generate them if they don't exist.""" global tokens for idx, client_secret in enumerate(client_secret_files): token_path = f"token_{idx}.pickle" credentials = None if os.path.exists(token_path): with open(token_path, 'rb') as token_file: credentials = pickle.load(token_file) logging.debug(f"Loaded token from {token_path}") if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) logging.debug(f"Refreshed expired token for {token_path}") else: flow = InstalledAppFlow.from_client_secrets_file(client_secret, SCOPES) credentials = flow.run_local_server(port=0) logging.debug(f"Generated new token from {client_secret}") with open(token_path, 'wb') as token_file: pickle.dump(credentials, token_file) logging.debug(f"Saved token to {token_path}") tokens.append(credentials)def authenticate_youtube_api():"""Authenticate and return the YouTube API service using the current token.""" global current_token_index, tokens if not tokens: load_tokens() creds = tokens[current_token_index] return build('youtube', 'v3', credentials=creds)def switch_token_on_quota_error():"""Switch to the next token if the quota has been exceeded.""" global current_token_index, tokens current_token_index = (current_token_index + 1) % len(tokens) logging.warning(f"Switched to token {current_token_index + 1}")# from other functionexcept HttpError as e: if e.resp.status == 403 and "quotaExceeded" in str(e): logging.warning("Quota exceeded for current token, switching token...") switch_token_on_quota_error() else: logging.error(f"Error fetching comments for video {video_id}: {e}") return []I was expecting the code to switch token.pickle files (token_0.pickle; token_1.pickle).Note: when i authenticate the 2 client_secret files, they are written to pickle files for security.
However when i call the function switch_token_on_quota_error() it fails to switch to the other pickle token (token_1.pickle).
How can I successfully switch between these 2 when the quotaExceeded error occurs?Not looking for answers that don't include fixes or help to fix it. I know Google doesn't like this, it's strictly for a test project that will never be used other than for my test.