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
posta un anno fa239 visualizzazioni
2 Risposte
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
ESPERTO
con risposta un anno fa
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
ESPERTO
con risposta un anno fa

Accesso non effettuato. Accedi per postare una risposta.

Una buona risposta soddisfa chiaramente la domanda, fornisce un feedback costruttivo e incoraggia la crescita professionale del richiedente.

Linee guida per rispondere alle domande