implement try/except on python with kubernetes python client with GKE

1.2k views Asked by At

How do I implement a try and except on my python script, I am using the kubernetes python client to communicate with my GKE cluster. And I want to create a deployment if it doesn't exists. I am currently doing this (code below) but it doesn't seem to work as it returns an API exception error and the program crashes.

Here is my current implementation

def get_job():
    conn.connect()
    api = client.CustomObjectsApi()

    for message in consumer:
        message = message.value
        try:
            resource = api.get_namespaced_custom_object(
                        group="machinelearning.seldon.io",
                        version="v1",
                        name=message["payload"]["metadata"]["name"],
                        namespace="seldon",
                        plural="seldondeployments",
                    ) # execution stops here and doesn't move to the next step.
                
            api.create_namespaced_custom_object(
                    group="machinelearning.seldon.io",
                    version="v1",
                    namespace="seldon",
                    plural="seldondeployments",
                    body=message['payload'])
            print("Resource created")
                    print(e)
            else:
                pass

How can I fix this? The logic I am trying to follow is this

  1. If the deployment exists, return a already exist message without crashing the script.
  2. If the deployment doesn't exist, create a new deployment.
1

There are 1 answers

0
AzyCrw4282 On BEST ANSWER

I am currently doing this (code below) but it doesn't seem to work as it returns an API exception error and the program crashes.

The reason it crashes is due to no handling of exception within the code. Your approach also seems flawed. Your try statements can be split into something like this (credit)

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

So what you have to do is add the operations as where they are required to be.

If the deployment exists, return a already exist message without crashing the script.

You can handle this in the else statement and simply print a message to state that it already exists.

If the deployment doesn't exist, create a new deployment.

You can add this operation within the except part of the try statement, so when an error is thrown it will catch it and perform the operation as you specified.