Переключение между учетными данными проекта API YouTube ⇐ Python

Программы на Python
Anonymous
Переключение между учетными данными проекта API YouTube

Сообщение Anonymous »

У меня есть 2 проекта API YouTube, я хочу, чтобы мой код переключался между двумя файлами (token.pickle) при возникновении ошибки превышения квоты.
Ниже показано, что я пробовал:

Код: Выделить всё

SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']

# List of client secret files for different projects
client_secret_files = ['client_secret.json', 'client_secret2.json']

# Holds active tokens
tokens = []
current_token_index = 0

def 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 function
except 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 []

Я ожидал, что код переключит файлы token.pickle (token_0.pickle; token_1.pickle).
Примечание: когда я аутентифицирую 2 файла client_secret, они записываются в файлы Pickle для обеспечения безопасности.
Однако, когда я вызываю функцию switch_token_on_quota_error(), она не может переключиться на другой токен Pickle (token_1.pickle).
Как я могу успешно переключаться между этими двумя вариантами при возникновении ошибки quotaExceeded?
Не ищу ответы, которые не содержат исправлений или не помогают ее исправить. Я знаю, что Google это не нравится, это строго тестовый проект, который никогда не будет использоваться кроме как для моего теста.

Подробнее здесь: https://stackoverflow.com/questions/790 ... redentials

Вернуться в «Python»