gpt4 book ai didi

python - 如何在不使用 gcloud auth login 创建的凭据文件的情况下初始化 GoogleCredentials 对象

转载 作者:行者123 更新时间:2023-11-28 22:43:37 25 4
gpt4 key购买 nike

要连接到 GCE,我可以使用 gcloud auth login 创建的凭据文件。像这样:

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build

credentials = GoogleCredentials.get_application_default()
compute = build('compute', 'v1', credentials=credentials)

def list_instances(compute, project, zone):
result = compute.instances().list(project=project, zone=zone).execute()
return result['items']

instances = list_instances(compute, 'project', 'zone')

以上代码使用存储在 ~/.config/gcloud 的凭据

我想通过直接在代码中设置值来初始化 GoogleCredentials 对象。比如client_id, client_secret..

PS:以上代码来自此链接:https://cloud.google.com/compute/docs/tutorials/python-guide#gettingstarted

最佳答案

还有另一种初始化 GoogleCredentials 对象的方法:

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials
from urllib import urlencode
from urllib2 import Request , urlopen, HTTPError
import json

def access_token_from_refresh_token(client_id, client_secret, refresh_token):
request = Request('https://accounts.google.com/o/oauth2/token',
data=urlencode({
'grant_type': 'refresh_token',
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token
}),
headers={
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
)
response = json.load(urlopen(request))
return response['access_token']

access_token = access_token_from_refresh_token('client_id', 'client_secret', 'refresh_token')

credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None)

compute = build('compute', 'v1', credentials=credentials)

def list_instances(compute, project, zone):
result = compute.instances().list(project=project, zone=zone).execute()
return result['items']

instances = list_instances(compute, 'project', 'zone')

--client_id、secret、refresh_token 的值取自 ~/.config/gcloud/credentials

关于python - 如何在不使用 gcloud auth login 创建的凭据文件的情况下初始化 GoogleCredentials 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544510/

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