python-3.x - 使用Python客户端库进行gcp计算API使用什么以及如何传递凭据

标签 python-3.x google-cloud-platform google-api-client

我想使用python google client api google-api-python-client==1.7.11获取项目中所有实例的列表
我正在尝试使用方法googleapiclient.discovery.build进行连接,此方法需要凭据作为参数

我阅读了文档,但未获得凭证格式以及所需的凭证

任何人都可以解释什么凭证以及如何通过以建立gcp连接

最佳答案

您所需的凭据称为“服务帐户JSON key 文件”。这些是在Google Cloud Console中的IAM和管理/服务帐户下创建的。创建一个服务帐户并下载 key 文件。在下面的示例中,这是service-account.json

使用服务帐户的示例代码:

from googleapiclient import discovery
from google.oauth2 import service_account

scopes = ['https://www.googleapis.com/auth/cloud-platform']
sa_file = 'service-account.json'
zone = 'us-central1-a'
project_id = 'my_project_id' # Project ID, not Project Name

credentials = service_account.Credentials.from_service_account_file(sa_file, scopes=scopes)

# Create the Cloud Compute Engine service object
service = discovery.build('compute', 'v1', credentials=credentials)

request = service.instances().list(project=project_id, zone=zone)
while request is not None:
    response = request.execute()

    for instance in response['items']:
        # TODO: Change code below to process each `instance` resource:
        print(instance)

    request = service.instances().list_next(previous_request=request, previous_response=response)

关于python-3.x - 使用Python客户端库进行gcp计算API使用什么以及如何传递凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57589526/

相关文章:

SSL23_GET_SERVER_HELLO :unknown protocol

android - 使用 GoogleApiClient 的定位后台服务

android - FragmentActivity:为未知 Fragment 传递的 Activity 结果

java - Android 地理围栏不触发 IntentService

google-cloud-platform - GCP API key 管理员角色

google-cloud-platform - 从 Autopilot GKE 集群访问 Google Cloud Storage

python-3.x - 使用 Python3 Pytesseract 进行实时屏幕监控

python-3.x - 如何区分物体曲率的两种不同类型的异常?

ruby - Ruby 是否具有与 Python 中的 __pycache__ 文件夹等效的功能?

python - Python 可停止线程是否需要守护进程或 .join()?