I am creating a basic flask app that outputs a list of instances running on a GCP project into the browser but I'm coming across some issues when returning the result of the api call inside the browser.
My flask app looks something like this:
@app.route(API_ROOT + 'list')
def list_all_running():
return test_list.list_all_running_instances()
and the function I'm trying to return looks like this
def list_all_running_instances():
request = service.instances().list(project=project, zone='europe-west1-d')
while request is not None:
response = request.execute()
for instance in response['items']:
# if instance['status'] == 'RUNNING':
return instance
request = service.instances().list_next(previous_request=request, previous_response=response)
This is a shortened and adapted version of this script listed under 'python' in the examples at the bottom of the page.
The issue is when I call the function in flask it only returns the first instance running. In the original gcp api script example it uses pprint
rather than return, which works fine on the console but I am unable to output the pprint
results to a browser.
Can anyone recommend the best way of doing this? Is there a way you can output pprint
into the browser via Flask. I realise that when returning it will only output the result of the first iteration and then stop, hence this issue.
As you can tell I'm quite new at Flask, so apologies if this seems like a silly question.
The problem is the return
statement which finishes execution of your list_all_running_instances
function. You can do something like this:
def list_all_running_instances():
request = service.instances().list(project=project, zone='europe-west1-d')
all_instances = []
while request is not None:
response = request.execute()
all_instances.extend(response['items'])
request = service.instances().list_next(previous_request=request, previous_response=response)
return {'all_instances': all_instances}