【问题标题】:How do you get gcloud access token in Python?如何在 Python 中获取 gcloud 访问令牌?
【发布时间】:2019-12-09 21:52:11
【问题描述】:

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

【问题讨论】:

标签: python gcloud


【解决方案1】:

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

    答案在这里:

    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)
    

    【讨论】:

      【解决方案3】:

      使用python:

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

      【讨论】:

        猜你喜欢
        • 2021-02-04
        • 1970-01-01
        • 2012-05-16
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 2012-02-15
        • 2019-08-12
        相关资源
        最近更新 更多