Ошибка при определении учетных данных и API YouTube

#python #google-api #youtube-api #google-api-python-client

#python #google-api #youtube-api #google-api-python-client

Вопрос:

Обновление: Исправление: — Просто понял, что мне не хватает следующего из моего .bashrc

вы можете обновить исходный профиль bash с помощью переменной среды

 if [ -f ~/.bash_profile ]; then
   . ~/.bash_profile
fi
  

Я пытаюсь использовать скрипты API от corey schafer с YouTube. Недавно я сменил свой текстовый редактор на VSCode из Sublime text.

Я ожидал вывода, как показано ниже, из Sublime text,

 {'kind': 'youtube#channelListResponse', 'etag': '-bp4b5Yy0e-HRWQsadmZk2A75GE', 'pageInfo': {'totalResults': 1, 'resultsPerPage': 5}, 'items': [{'kind': 'youtube#channel', 'etag': 'vakSZODpMKK8i9f3UStrRvd2sQA', 'id': 'UCCezIgC97PvUuR4_gbFUs5g', 'statistics': {'viewCount': '47863717', 'subscriberCount': '667000', 'hiddenSubscriberCount': False, 'videoCount': '230'}}]}
[Finished in 1.0s]
  

Я получаю следующую ошибку, пожалуйста, обратите внимание, что я переименовал python в python3
Я новичок. пожалуйста, дайте мне знать, если я упускаю что-то основное

 python -u "/Users/natluri/Documents/ytproj/youtubeapi.py"
Traceback (most recent call last):
  File "/Users/natluri/Documents/ytproj/youtubeapi.py", line 5, in <module>
    youtube = build('youtube', 'v3', developerKey=api_key)
  File "/usr/local/lib/python3.9/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/googleapiclient/discovery.py", line 278, in build
    service = build_from_document(
  File "/usr/local/lib/python3.9/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/googleapiclient/discovery.py", line 527, in build_from_document
    credentials = _auth.default_credentials(
  File "/usr/local/lib/python3.9/site-packages/googleapiclient/_auth.py", line 54, in default_credentials
    credentials, _ = google.auth.default(scopes=scopes, quota_project_id=quota_project_id)
  File "/usr/local/lib/python3.9/site-packages/google/auth/_default.py", line 356, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
  

Комментарии:

1. Похоже, что ваш файл учетных данных Google отсутствует.

2. Не удалось автоматически определить учетные данные. Пожалуйста, установите GOOGLE_APPLICATION_CREDENTIALS или явно создайте учетные данные и повторно запустите приложение. швы вполне понятны.

Ответ №1:

Поскольку вы не опубликовали свой код, трудно помочь вам исправить ваш код, однако ниже должен быть пример того, как авторизовать API YouTube без использования env var.

 SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_youtube():
  """Initializes the youtube service object.

  Returns:
    analytics an authorized youtube service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('youtube.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  youtube = build('youtube', 'v3', http=http)

  return youtube