Search code examples
pythongoogle-app-enginelocation

how to get locationId in Google App Engine not using terminal


To use scheduler_v1.CloudSchedulerClient().location_path() in Python I need parent with projectId and LocationId. I know how to get projectId in code and locationId from terminal, but how to do it in my code?

I've tried to check this website(https://cloud.google.com/functions/docs/reference/rpc/google.cloud.location), but there are no examples, idk what to do with it

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)

Thank you!


Solution

  • It is not necessary to use cloudresourcemanager to get the project ID, instead you can use the App Engine environment variable GOOGLE_CLOUD_PROJECT

    You can use App engine admin API to get the location ID please check this code snippet.

        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"])