如何在Python中获取gcloud访问令牌?

时间:2019-12-09 21:52:11

标签: python gcloud

我正在寻找在Python中执行以下等效操作的方法,而不必使用os.system之类的命令来调用这些命令并查看输出。

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"
export PROJECT_ID="my-project-name"
gcloud auth application-default print-access-token

这可以通过Google SDK完成吗?

3 个答案:

答案 0 :(得分:0)

使用python:

  import request       
  requests.get('http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token').json().get('access_token')

答案 1 :(得分:0)

我认为您可以使用Google Auth Library来做到这一点。您可以使用pip安装它:

$ pip install google-auth

下面是使用存储桶的示例代码:

from google.oauth2 import service_account
from google.cloud import storage


KEY='/path/to/key.json'
PROJECT='your_project_id'

# gcloud auth application-default print-access-token is no necessary
credentials = service_account.Credentials.from_service_account_file(KEY)


# Initialize the Cloud Storage client using the credentials
storage_client = storage.Client(PROJECT,credentials)

# List objects in a bucket
blobs = storage_client.list_blobs("a_bucket")

for blob in blobs:
    print(blob.name)

祝你好运!

答案 2 :(得分:0)

答案在这里:

import google.auth
import google.auth.transport.requests

from google.oauth2 import service_account
from os.path import expanduser
from os import getenv

# The the service account key ABSOLUTE path from env or current folder
service_account_key = getenv(
    'GOOGLE_APPLICATION_CREDENTIALS',
    f'{expanduser(".")}/service-account-key.json'
)

# Creates a credentials object from the service account file
credentials = service_account.Credentials.from_service_account_file(
    service_account_key, # key path
    scopes=['https://www.googleapis.com/auth/cloud-platform'] # scopes
)

# Prepare an authentication request
auth_req = google.auth.transport.requests.Request()

# Request refresh tokens
credentials.refresh(auth_req)

# now we can print the access token
print(credentials.token)