首页 > 解决方案 > 如何在不使用终端的 Google App Engine 中获取 locationId

问题描述

要在 Python 中使用 scheduler_v1.CloudSchedulerClient().location_path(),我需要具有 projectId 和 LocationId 的父级。我知道如何从终端获取代码中的 projectId 和 locationId,但是如何在我的代码中获取呢?

我试过检查这个网站(https://cloud.google.com/functions/docs/reference/rpc/google.cloud.location),但没有例子,idk怎么处理它

from google.cloud import scheduler_v1


from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('/home/myname/folder/service_account.json')
service = googleapiclient.discovery.build('cloudresourcemanager', 'v1', credentials = credentials)
request = service.projects().list()
response = request.execute()
client = scheduler_v1.CloudSchedulerClient()

for project in response['projects']:
    parent = client.location_path(project['projectId'], ['LocationID'])
    for element in client.list_jobs(parent):
        print(element)

谢谢!

标签: pythongoogle-app-enginelocation

解决方案


获取项目 ID不需要使用cloudresourcemanager,可以使用 App Engine 环境变量GOOGLE_CLOUD_PROJECT

您可以使用App engine admin API获取位置 ID,请检查此代码段。

    credentials = GoogleCredentials.get_application_default()
    #start discovery service and use appengine admin API
    service = discovery.build('appengine', 'v1', credentials=credentials, cache_discovery=False)

    #disable cache for app engine std (avoid noise in logs)
    logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

    #take the project ID form the environment variables
    project = os.environ['GOOGLE_CLOUD_PROJECT']

    #get App engine application details
    req = service.apps().get(appsId=project)

    response =req.execute()

    #this is the application location id
    location_id = (response["locationId"])

推荐阅读