开发者社区> 问答> 正文

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

我正在尝试通过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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 09:42:56 1103 0
1 条回答
写回答
取消 提交回答
  • 我认为您的脚本有效。实际上,在我的环境中,我可以确认您的脚本有效。

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

    2020-03-25 00:01:20
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载