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

Vik*_*ngh 3 python google-compute-engine

要连接到 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')
Run Code Online (Sandbox Code Playgroud)

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

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

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

Vik*_*ngh 5

还有另一种初始化 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')
Run Code Online (Sandbox Code Playgroud)

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

  • 现在工作..我宁愿不添加刷新令牌,因为我不知道它什么时候会过期。你能告诉我刷新令牌是如何工作的,以便我可以在需要时更新值。 (2认同)