google.oauth2.credentials.Credentials失败,带有有效令牌

问题描述 投票:0回答:1

[我正在尝试通过Python 3.6列出我的YouTube频道,因为(这很重要)已有访问令牌和一些有效的API密钥。它可以很好地配合curl并返回有效的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": [...]
}

如果删除授权标头,则会出现预期的错误:

{
    "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代码(请注意,访问令牌已赋予代码,我必须原样使用):

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
python-3.x youtube-data-api google-oauth2
1个回答
0
投票

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

在您的情况下,您已经获得了访问令牌。我认为,在这种情况下,当访问令牌可用于使用Youtube Data API时,脚本就可以使用,而无需使用API​​密钥。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.