在没有每次身份验证的情况下可以使用Google Api吗? [英] Any way to use Google Api without every-time authentication?

查看:56
本文介绍了在没有每次身份验证的情况下可以使用Google Api吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to use the API on python in a autorun on a PC. But I can't because every time the program starts, it asks me about the authorization code. This is my code:

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.

Becouse you are using the YouTube API you can not use a service account you will need to use Oauth2.

Oauth2可以返回称为刷新令牌的内容,如果您存储此令牌,则代码可以在下次运行时访问刷新令牌,并使用刷新令牌以这种方式请求新的访问令牌,而无需询问您每当它运行以访问您的数据时.

Oauth2 can return something called a refresh token, if you store this token your code can then access the refresh token the next time it runs and use the refresh token to request a new access token this way it will not need to ask you every time it runs to access your data.

# 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快速入门您将需要为YouTube对其进行更改,但是实际上您只需要使用身份验证代码,只需将其插入您的代码即可,您应该是GTG

The only offical sample that includes refresh token that i know if is here Python quickstart you will need to alter it for YouTube but the auth code is really all you need just plug that int your code and you should be GTG

这篇关于在没有每次身份验证的情况下可以使用Google Api吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆