使用kubernetes python客户端和GKE在python上实现try/except

2024-09-26 18:02:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何实现一个try,除了在我的python脚本上,我正在使用kubernetes python客户机与我的GKE集群通信。如果部署不存在,我想创建一个部署。我目前正在这样做(下面的代码),但它似乎不起作用,因为它返回一个API异常错误,程序崩溃

这是我当前的实现

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

我怎样才能解决这个问题? 我试图遵循的逻辑是

  1. 如果部署存在,则在不使脚本崩溃的情况下返回“已存在”消息
  2. 如果部署不存在,请创建新部署

Tags: io脚本apimessagegetobjectversion部署
1条回答
网友
1楼 · 发布于 2024-09-26 18:02:23

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.

它崩溃的原因是代码中没有处理异常。你的方法似乎也有缺陷。您的try语句可以拆分为以下内容(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

因此,您需要做的是将操作添加到所需的位置

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

您可以在else语句中处理这个问题,只需打印一条消息以声明它已经存在

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

您可以在try语句的except部分中添加此操作,因此当抛出错误时,它将捕获错误并按照您指定的方式执行操作

相关问题 更多 >

    热门问题