google.oauth2.credentials.Credentials 使用有效令牌失败

google.oauth2.credentials.Credentials fails with valid token

我正在尝试通过 Python 3.6 列出我的 YouTube 频道,给定(这很重要)一个现有的访问令牌和一些有效的 API 密钥。它适用于 curl 和 returns 有效的 JSON 响应:

curl 'https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true&key=API_KEY' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer ACCESS_TOKEN'

回复:

{
    "kind": "youtube#channelListResponse",
    "etag": "\"xxxxxxxxx\"",
    "pageInfo": {...},
    "items": [...]
}

如果我删除授权 header,我会得到预期的错误:

{
    "error": {
        "errors": [
            {
                "domain": "youtube.parameter",
                "reason": "authorizationRequired",
                "message": "The request uses the <code>mine</code> parameter but is not properly authorized.",
                "locationType": "parameter",
                "location": "mine"
            }
        ],
        "code": 401,
        "message": "The request uses the <code>mine</code> parameter but is not properly authorized."
    }
}

现在,我尝试对 Google Python 库做同样的事情(因为我需要它来进行更复杂的操作和代码控制),但它不起作用。我得到了同样的错误,就好像我没有传递任何访问令牌一样。任何想法我做错了什么?这是我的 Python 代码(注意访问令牌已提供给代码,我必须使用它 as-is):

import argparse
import google.oauth2.credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def get_authenticated_service(options):
  creds = google.oauth2.credentials.Credentials(options.access_token)
  return build('youtube', 'v3', credentials=creds, developerKey=options.api_key)

def list_channels(youtube, options):
  request = youtube.channels().list(part="snippet", mine=True)
  response = request.execute()
  print(response)

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--api_key', required=True)
  parser.add_argument('--access_token', required=True)
  args = parser.parse_args()
  youtube = get_authenticated_service(args)
  try:
    list_channels(youtube, args)
  except HttpError as e:
    print('An HTTP error {0} occurred:\n{1}'.format(e.resp.status, e.content))

我运行是这样的:

python3 test.py --api_key MY_API_KEY --access_token MY_ACCESS_TOKEN

我认为您的脚本有效。实际上,在我的环境中,我可以确认您的脚本有效。

在您的情况下,您已经获得了访问令牌。我认为当访问令牌可用于使用 Youtube 数据 API 时,在这种情况下,脚本无需使用 API 键即可工作。

参考: