gpt4 book ai didi

python - 在 python 中执行 oauth2 headless 对抗 google api

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:16 26 4
gpt4 key购买 nike

Google 的 YouTube Analytics API 仅基于 Oauth2。我正在使用以下测试脚本来查看是否可以获得访问权限:

import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']

API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'client_secret.json'
def get_service():
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

def execute_api_request(client_library_function, **kwargs):
response = client_library_function(
**kwargs
).execute()

print(response)

if __name__ == '__main__':
# Disable OAuthlib's HTTPs verification when running locally.
# *DO NOT* leave this option enabled when running in production.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

youtubeAnalytics = get_service()
execute_api_request(
youtubeAnalytics.reports().query,
ids='channel==MINE',
startDate='2017-01-01',
endDate='2017-12-31',
metrics='estimatedMinutesWatched,views,likes,subscribersGained',
dimensions='day',
sort='day'
)

我的问题是这个脚本要求我打开浏览器,设置链接,登录,然后获取 token 电缆。

有什么方法可以在“ headless ”模式下做到这一点吗?我需要提取这些 API 来进行机器到机器的传输。

谢谢!

最佳答案

执行一次,然后将credentials = flow.run_console()返回的凭据对象保存到数据库或文件中。其中包含一个可在后续 api 调用中使用的“刷新 token ”,这意味着您可以跳过 flow.run_console 步骤,只需在 build(API_SERVICE_NAME, API_VERSION,凭证 = 凭证) 调用。

这里的文档中有关于此的注释:

https://developers.google.com/youtube/reporting/guides/authorization/installed-apps#exchange-authorization-code

关于python - 在 python 中执行 oauth2 headless 对抗 google api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com