except block is not working in try except in python

0

I am trying to get list of pods from specific namespace in aws lambda (python).

Its giving right and expected list of pods. But When I pass wrong namespace, it is not skipping the try block and not catching the except block to return the correct response. Any reason for this ?

`import json from kubernetes.client.rest import ApiException

def get_pods(namespace: str, apiCoreclient: object):

response_output = {}
response_output["statusCode"] = 200    

retList = []
items = apiCoreclient.list_namespaced_pod(namespace).items
for item in items:
    try:
        retList.append(item.metadata.name)
        response_output['Pods'] = json.dumps({"Pods": retList})

    except ApiException as e:
        response_output["error"] = e.reason
        response_output["statusCode"] = e.status

response_output["isBase64Encoded"] = "False"       
return json.dumps(response_output)`
profile picture
asked 10 months ago227 views
2 Answers
0

Exception handling catches any occurrences within a try.
I think we need to put "items = apiCoreclient.list_namespaced_pod(namespace).items" in the try to get the list of pods.
So I thought it was necessary to do the following.

import json 
from kubernetes.client.rest import ApiException

def get_pods(namespace: str, apiCoreclient: object):

response_output = {}
response_output["statusCode"] = 200    

retList = []
try:
    items = apiCoreclient.list_namespaced_pod(namespace).items
    for item in items:
        retList.append(item.metadata.name)
        response_output['Pods'] = json.dumps({"Pods": retList})
except ApiException as e:
    response_output["error"] = e.reason
    response_output["statusCode"] = e.status

response_output["isBase64Encoded"] = "False"       
return json.dumps(response_output)
profile picture
EXPERT
answered 10 months ago
0

Hi,

In order to prevent unauthorized users sniffing the existence of namespace, Kubernetes returns a 200 HTTP status code with an empty items array when it does not exist. Therefore, I think that your application behaves as is.

kubectl get --raw /api/v1/namespaces/non-exist/pods
{"kind":"PodList","apiVersion":"v1","metadata":{"selfLink":"/api/v1/namespaces/non-exist/pods","resourceVersion":"12568447"},"items":[]}

(Example copied from the following Kubernetes Github issue)

profile picture
EXPERT
answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions