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
質問済み 1年前238ビュー
2回答
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
エキスパート
回答済み 1年前
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
エキスパート
回答済み 1年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ