有没有办法不用每次验证就使用Google Api?

2024-03-24

我尝试在 PC 上的自动运行中使用 python 上的 API。但我不能,因为每次程序启动时,它都会询问我授权码。 这是我的代码:

client_secret_file = "client_secret.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

有什么帮助吗?谢谢


由于您使用的是 YouTube API,因此无法使用服务帐户,因此需要使用 Oauth2。

Oauth2 可以返回称为刷新令牌的东西,如果您存储此令牌,您的代码就可以在下次运行时访问刷新令牌,并使用刷新令牌请求新的访问令牌,这样就不需要每次都询问您运行以访问您的数据。

# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

我知道的唯一包含刷新令牌的官方示例在这里Python 快速入门 https://developers.google.com/people/quickstart/python你需要为 YouTube 更改它,但授权代码确实是你所需要的,只需将其插入你的代码中,你应该是 GTG

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法不用每次验证就使用Google Api? 的相关文章

随机推荐