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
- If the deployment exists, return a already exist message without crashing the script.
- If the deployment doesn't exist, create a new deployment.
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)
So what you have to do is add the operations as where they are required to be.
You can handle this in the
else
statement and simply print a message to state that it already exists.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.