没有每次验证都可以使用Google Api吗?

问题描述

我试图在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 quickstart上,您需要为YouTube对其进行更改,但是身份验证代码实际上就是您所需要的,只需插入该代码即可,您应该是GTG

,

您可以使用Service帐户来实现此目的。

https://googleapis.dev/python/google-api-core/latest/auth.html#service-accounts

服务帐户在技术上已得到开发人员的预先授权。

如果该API不支持服务帐户(在某些情况下),那么您可以尝试oauth2,如果您同意询问该帐户的所有者是否可以访问