在 python 客户端中关闭与 kubernetes API 服务器的客户端连接

Closing client connection to kubernetes API server in python client

例如,我正在使用 kubernetes-client library in python and looking at the various examples, it appears we don't need to explicitly close the client connection to the API server. Does the client connection gets terminated automatically or are the examples missing the call to close the connection? I also found the docs page for the APIs (AppsV1)并且那里显示的示例使用上下文管理器进行调用,因此连接在那里自动断开,但我仍然对不使用上下文管理器的脚本有疑问方法。

Kubernetes 的 API 是基于 HTTP 的,因此您通常可以在不显式关闭连接的情况下逃脱。如果您有一个简短的脚本,应该会在脚本结束时自动清理这些内容,并且可以不显式关闭这些内容。

您 link 的特定文档页面显示了一种安全的方法:

with kubernetes.client.ApiClient(configuration) as api_client:
    api_instance = kubernetes.client.AppsV1Api(api_client)
    api_instance.create_namespaced_controller_revision(...)

如果您将 ApiClient 传递给其构造函数,则每个 API 版本的客户端对象是无状态的,因此根据需要创建这些对象是安全的。

ApiClient class includes 一个明确的 close 方法,所以你也可以在没有上下文管理器语法的情况下这样做(不太安全):

api_client = kubernetes.client.ApiClient(configuration)
apps_client = kubernetes.client.AppsV1Api(api_client)
...
api_client.close()

图书馆客户端首页 README 建议了一条未明确创建 ApiClient 的路径。查看 one of the generated models' code,如果您没有显式传递 ApiClient 选项,将为每个 API-version 客户端对象创建一个新的;这也包括一个连接池。这可能会泄漏本地内存并导致与集群的额外连接,但对于小型脚本来说这可能无关紧要。