繁体   English   中英

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

[英]How do you get gcloud access token in Python?

我希望在 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 完成吗?

我认为您可以使用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)

祝你编码好运!

使用蟒蛇:

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

答案在这里:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM