【发布时间】:2017-02-22 23:36:26
【问题描述】:
我正在尝试使用 Python 连接到 YouTube Analytics API。当我转到凭据选项卡中的 Google 开发人员控制台时,我单击 Create credentials 下拉菜单并选择 Help me choose。我点击我想使用的 API (YouTube Analytics API),我将从那里调用 (Other non-UI (e.g. cron job, daemon)),我将访问哪些数据 (Application Data),然后我是否使用 Google App Engine ( no)。我点击按钮查看我需要哪些凭据,它会告诉我You alread have credentials that are suitable for this purpose。
我有一个 Service account 用于连接到 Google Search Console API 以访问我公司拥有的多个网站的数据。因为我们有多个站点,所以我根据我的电子邮件地址使用委托凭据。这是我用来向 Search Console API 进行身份验证的代码:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scopes = ['https://www.googleapis.com/auth/webmasters.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())
webmasters_service = build('webmasters', 'v3', http=http_auth)
现在,我正在尝试对 YouTube 分析 API 使用类似的方法,但出现此错误:HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request.。这是我的代码:
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
START_DATE = "2016-09-01"
END_DATE = "2016-09-30"
scopes = ['https://www.googleapis.com/auth/yt-analytics.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())
youtube_service = build('youtubeAnalytics', 'v1', http=http_auth)
analytics_query_response = youtube_service.reports().query(
ids="channel==<my-youtube-channel-id>",
metrics="views",
start_date=START_DATE,
end_date=END_DATE
).execute()
keyfile.json 是我用来连接到 Search Console API 的同一个文件(包含服务帐户凭据)。我什至尝试创建一个新的服务帐户并使用这些凭据,但我没有任何运气。是的,我已经在开发者控制台中启用了所有的 YouTube API。
你知道我为什么会收到HttpAccessTokenRefreshError: unauthorized_client: ... 错误吗?
编辑:以前我使用 OAuth ID 而不是服务帐户,当我运行我的脚本时,会出现一个浏览器选项卡,我必须选择一个帐户。我看到了两个选项:一个是我的电子邮件,另一个是我被添加为经理的 YouTube 帐户。您认为我收到该错误是因为我使用我的电子邮件地址(而不是 YouTube 帐户)来生成凭据吗?
edit2:YouTube 帐户似乎不属于我们的 Google Apps 域。因此,这可能就是我无法授权使用我的电子邮件地址的原因,即使我已成为使用该电子邮件地址的 YouTube 帐户的管理员。
【问题讨论】:
-
您是否启用了通过您的 IP 从控制台访问
-
@UnknownDeveloper 我不知道该怎么做,但是在连接到 Google Search Console API 时我不会遇到同样的错误吗?我对 Search Console API 没有任何问题,只有 YouTube Analytics API。仅供参考,我在我的问题中添加了更多信息,描述了我使用 OAuth 方法时发生的情况。
标签: python youtube-api google-oauth google-api-client