简体   繁体   English

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

[英]Closing client connection to kubernetes API server in python client

I am using kube.netes-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.我在 python 中使用kube.netes-client库并查看各种示例,看来我们不需要显式关闭与 API 服务器的客户端连接。 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 for example) and the examples shown there use context manager for the calls so the connection gets disconnected automatically there but I still have questions for the scripts that don't use the context manager approach.我还找到了 API 的文档页面(例如AppsV1 ),那里显示的示例使用上下文管理器进行调用,因此连接在那里自动断开,但我仍然对不使用上下文管理器方法的脚本有疑问。

Kube.netes's API is HTTP-based, so you can often get away without explicitly closing a connection. Kube.netes 的 API 是基于 HTTP 的,因此您通常可以在不显式关闭连接的情况下逃脱。 If you have a short script, things should get cleaned up automatically at the end of the script and it's okay to not explicitly close things.如果您有一个简短的脚本,应该会在脚本结束时自动清理所有内容,并且可以不显式关闭这些内容。

The specific documentation page you link to shows a safe way to do it:您链接到的特定文档页面显示了一种安全的方法:

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

The per-API-version client object is stateless if you pass in an ApiClient to its constructor, so it's safe to create these objects as needed.如果将ApiClient传递给其构造函数,则每个 API 版本的客户端 object 是无状态的,因此根据需要创建这些对象是安全的。

The ApiClient class includes an explicit close method, so you could also do this (less safely) without the context-manager syntax: ApiClient class 包含一个明确的close方法,因此您也可以在没有上下文管理器语法的情况下执行此操作(不太安全):

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

The library client front-page README suggests a path that doesn't explicitly create an ApiClient .库客户端首页README建议了一条未明确创建ApiClient的路径。 Looking at one of the generated models' code , if you don't pass an ApiClient option explicitly, a new one will be created for each API-version client object;查看其中一个生成的模型代码,如果您没有明确传递ApiClient选项,将为每个 API 版本客户端创建一个新的 object; that includes a connection pool as well.这也包括一个连接池。 That can leak local memory and cause extra connections to the cluster, but this might not matter to you for small scripts.这可能会泄漏本地 memory 并导致与集群的额外连接,但这对于小脚本来说可能无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM