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
gefragt vor einem Jahr237 Aufrufe
2 Antworten
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
EXPERTE
beantwortet vor einem Jahr
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
EXPERTE
beantwortet vor einem Jahr

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen