如何在Python中获取gcloud访问令牌? [英] How do you get gcloud access token in Python?
本文介绍了如何在Python中获取gcloud访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找在Python中执行以下等效操作的方法,而不必使用诸如os.system
之类的命令来调用这些命令并查看输出.
I'm looking to do the equivalent of the following in Python with out having to call these command using something like os.system
and look at the output.
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"
export PROJECT_ID="my-project-name"
gcloud auth application-default print-access-token
这可以通过Google SDK完成吗?
Can this be done with Google SDK?
推荐答案
我认为您可以使用 Google身份验证库.您可以使用pip
安装它:
I think you can do this using the Google Auth Library. You can install it with pip
:
$ pip install google-auth
以下是使用存储桶的示例代码:
Here's an example code using buckets:
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)
祝你好运!
这篇关于如何在Python中获取gcloud访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文