
后端云原生容器编排【免费下载链接】pythonOfficial Python client library for kubernetes项目地址https://gitcode.com/gh_mirrors/python1/python点击查看免费下载本文聚焦 pythonKubernetes 官方 Python 客户端中kubernetes.aio.client.api.autoscaling_api模块的异步 autoscaling API 组访问能力。以 autoscaling_api.rst 对应的 API 参考为核心结合同族的autoscaling_v1_api、autoscaling_v2_api源码与异步客户端使用示例读者将掌握如何通过AutoscalingApi.get_api_group()探测 autoscaling API 组的版本信息并在此基础上用AutoscalingV2Api完成 HPAHorizontalPodAutoscaler的创建、查询、更新与删除。autoscaling 模块族在异步客户端中的定位在kubernetes.aio.client.api目录下autoscaling 相关模块共有三个职责边界清晰模块文件类名覆盖的 API 组autoscaling_api.pyAutoscalingApi/apis/autoscaling/组级信息即本文关联文档主题autoscaling_v1_api.pyAutoscalingV1Api/apis/autoscaling/v1/旧版 HPA仅 CPU 指标autoscaling_v2_api.pyAutoscalingV2Api/apis/autoscaling/v2/当前推荐版本支持多指标三个模块均由 OpenAPI Generator 根据release-1.37版本的 Kubernetes OpenAPI 规范自动生成见 autoscaling_api.py 文件头注释因此方法签名、请求路径与 Kubernetes API Server 的 REST 语义严格对应。本文关联文档 autoscaling_api.rst 正是通过 Sphinx 的automodule指令对AutoscalingApi类生成的 API 参考页其全部技术实质都沉淀在该模块源码中。AutoscalingApi 类结构与生命周期管理AutoscalingApi类的构造与资源管理逻辑位于 autoscaling_api.pydef __init__(self, api_clientNone) - None: if api_client is None: api_client, owns_api_client ApiClient._get_default_or_new() else: owns_api_client False self.api_client api_client self._owned_api_client: Optional[ApiClient] ( api_client if owns_api_client else None ) async def close(self) - None: owned_api_client self._owned_api_client self._owned_api_client None if owned_api_client is not None: await owned_api_client.close() async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_value, traceback): await self.close()关键设计点客户端注入构造时可传入外部ApiClient如async with ApiClient() as api创建的会话不传时通过ApiClient._get_default_or_new()获取或新建默认客户端。所有权追踪从源码可见api_client属性保持公开可赋值但只有构造时内部新建的客户端才记入_owned_api_client。close()只关闭自有客户端避免误关外部共享会话。异步上下文管理器__aenter__/__aexit__让AutoscalingApi可以直接配合async with使用退出时自动关闭底层 HTTP 会话。核心方法get_api_group 探测 autoscaling 组信息AutoscalingApi的全部业务方法只有一个——get_api_group用于获取 autoscaling API 组的元信息支持的版本、首选版本等。方法定义见 autoscaling_api.pyvalidate_call(config{defer_build: True}) async def get_api_group( self, _request_timeout: Union[None, Annotated[StrictFloat, Field(gt0)], Tuple[Annotated[StrictFloat, Field(gt0)], Annotated[StrictFloat, Field(gt0)]]] None, _request_auth: Optional[Dict[StrictStr, Any]] None, _content_type: Optional[StrictStr] None, _headers: Optional[Dict[StrictStr, Any]] None, _host_index: Annotated[StrictInt, Field(ge0, le0)] 0, ) - V1APIGroup:请求参数说明这些参数是异步 API 客户端所有方法共享的统一控制参数各方法 docstring 均有详细说明参数类型默认值作用_request_timeoutfloat或(connection, read)元组None请求超时设置传单个数字表示总超时传二元组分别控制连接超时与读取超时_request_authdictNone覆盖单次请求的认证设置可忽略规范中的全局认证_content_typestrNone强制请求的 content-type_headersdictNone覆盖单次请求的 HTTP 头_host_indexint0覆盖单次请求的 host_index当前规范仅允许0由Field(ge0, le0)约束底层请求构造_get_api_group_serialize方法实际执行路径是先调用await self._get_api_group_serialize(...)构造请求再交给api_client.call_api。序列化逻辑位于 autoscaling_api.py从中可以看到请求的完整形态HTTP 方法GET资源路径/apis/autoscaling/Accept 头按优先级选择application/json、application/yaml、application/vnd.kubernetes.protobuf、application/cbor认证方案BearerTokenKubernetes 客户端默认的令牌认证响应处理与返回类型请求发出后_response_types_map: Dict[str, Optional[str]] { 200: V1APIGroup, 401: None, } response_data await self.api_client.call_api(*_param, _request_timeout_request_timeout) await response_data.read() return self.api_client.response_deserialize( response_dataresponse_data, response_types_map_response_types_map, ).data即HTTP 200 时反序列化为V1APIGroup模型401未认证时无返回体。response_deserialize会根据状态码在_response_types_map中查表选择目标模型。返回模型 V1APIGroup 解析get_api_group的返回对象V1APIGroup定义在 v1_api_group.py对应 Kubernetes 中APIGroup的完整语义字段类型说明api_versionstr对象表示形式的版本化 schema 标识apiVersionkindstr对象类型CamelCase如APIGroupnamestr组名必填即autoscalingpreferred_versionV1GroupVersionForDiscovery该组首选版本如v2server_address_by_client_cidrsList[V1ServerAddressByClientCIDR]客户端 CIDR 到服务端地址的映射帮助客户端选择网络效率最高的端点versionsList[V1GroupVersionForDiscovery]该组支持的所有版本列表从源码实现可以看到该模型基于 PydanticBaseModel并采用AliasChoices同时接受apiVersion/api_version两种输入形式validate_by_aliasTrue保证序列化时输出 Kubernetes 标准的驼峰 JSON 字段名extraforbid则意味着传入未声明字段会直接校验失败。模型还提供了to_dict(serialize...)、from_dict、to_json、from_json等便捷方法用于序列化转换。实战扩展用 AutoscalingV2Api 管理 HorizontalPodAutoscalerAutoscalingApi只负责组级信息探测真正的 HPA 业务操作在AutoscalingV2Apiautoscaling_v2_api.py与AutoscalingV1Api中。从方法清单autoscaling_v2_api.py可以归纳出 HPA 的完整 CRUD 能力方法HTTP 路径语义create_namespaced_horizontal_pod_autoscalerPOST /apis/autoscaling/v2/namespaces/{namespace}/horizontalpodautoscalers在命名空间内创建 HPAlist_namespaced_horizontal_pod_autoscalerGET .../horizontalpodautoscalers列出命名空间内 HPAlist_horizontal_pod_autoscaler_for_all_namespacesGET /apis/autoscaling/v2/horizontalpodautoscalers列出集群全部命名空间 HPAread_namespaced_horizontal_pod_autoscalerGET .../horizontalpodautoscalers/{name}读取单个 HPAread_namespaced_horizontal_pod_autoscaler_statusGET .../horizontalpodautoscalers/{name}/status读取 HPA 状态子资源patch_namespaced_horizontal_pod_autoscalerPATCH .../horizontalpodautoscalers/{name}部分更新 HPApatch_namespaced_horizontal_pod_autoscaler_statusPATCH .../horizontalpodautoscalers/{name}/status部分更新状态子资源replace_namespaced_horizontal_pod_autoscalerPUT .../horizontalpodautoscalers/{name}整体替换 HPAreplace_namespaced_horizontal_pod_autoscaler_statusPUT .../horizontalpodautoscalers/{name}/status整体替换状态子资源delete_namespaced_horizontal_pod_autoscalerDELETE .../horizontalpodautoscalers/{name}删除 HPAdelete_collection_namespaced_horizontal_pod_autoscalerDELETE .../horizontalpodautoscalers批量删除 HPAget_api_resourcesGET /apis/autoscaling/v2/获取 v2 组的资源列表AutoscalingV1Api的方法集合与 v2 一一对应仅请求路径中的版本段不同/apis/autoscaling/v1/...见 autoscaling_v1_api.py 中的resource_path定义。创建 HPA 的关键参数以create_namespaced_horizontal_pod_autoscalerautoscaling_v2_api.py为例除了统一控制参数外业务参数包括参数必填说明namespace是对象所属命名空间body是V2HorizontalPodAutoscaler模型即 HPA 的完整定义pretty否设为true时输出美化格式dry_run否传入All表示执行所有 dry-run 阶段但不持久化变更field_manager否与本次变更关联的实体名称需小于 128 字符且仅含可打印字符field_validation否服务端字段校验策略Ignore忽略未知字段、Warn发出告警但仍成功v1.23 默认、Strict存在未知或重复字段即报 BadRequest三种返回变体从方法清单可以看到每个业务方法都有三个变体源码中成组出现标准方法如read_namespaced_horizontal_pod_autoscaler反序列化后直接返回模型对象.data_with_http_info变体返回ApiResponse[T]包含原始 HTTP 状态码、响应头与响应体便于诊断_without_preload_content变体以_preload_contentFalse调用call_api直接返回RESTResponseType原始流式响应适合不关心反序列化、需要自行处理原始字节的场景。异步调用完整示例参考 examples_asyncio/list_pods.py 展示的异步客户端标准用法可以写出访问 autoscaling API 组的完整代码import asyncio from kubernetes.aio import client, config from kubernetes.aio.client.api_client import ApiClient async def main(): # 从默认位置加载 kubeconfig也可用 Configuration 类直接配置 await config.load_kube_config() # 使用上下文管理器退出时自动关闭 HTTP 会话 async with ApiClient() as api: # 1. 探测 autoscaling API 组的首选版本 autoscaling client.AutoscalingApi(api) group await autoscaling.get_api_group() print(autoscaling group name:, group.name) print(preferred version:, group.preferred_version.group_version) print(supported versions:, [v.group_version for v in group.versions]) # 2. 用 v2 版客户端列出指定命名空间的 HPA v2 client.AutoscalingV2Api(api) hpas await v2.list_namespaced_horizontal_pod_autoscaler( namespacedefault ) for hpa in hpas.items: print(hpa.metadata.name, hpa.status.current_replicas) if __name__ __main__: asyncio.run(main())几点实践要点会话复用所有 API 类共享同一个ApiClient实例可在一个async with块内完成组探测与 HPA 操作避免重复建连超时控制对慢集群可传_request_timeout30或_request_timeout(5, 30)分别限制连接与读取超时认证load_kube_config()加载的凭据会以 BearerToken 方案注入每次请求_get_api_group_serialize中的_auth_settings [BearerToken]也可通过_request_auth按请求覆盖。小结本文关联文档对应的AutoscalingApi是 Kubernetes Python 异步客户端接入 autoscaling API 组的入口get_api_group()一次 GET/apis/autoscaling/即可拿到该组的首选版本与全部版本列表返回的V1APIGroup模型与 API Server 的APIGroup结构严格对应。要真正操作 HPA则使用同族的AutoscalingV2Api或兼容旧集群的AutoscalingV1Api配合异步上下文管理器与共享ApiClient即可在 asyncio 应用中实现完整的 HPA 生命周期管理。赞分享后端云原生容器编排【免费下载链接】pythonOfficial Python client library for kubernetes项目地址https://gitcode.com/gh_mirrors/python1/python点击查看免费下载相关推荐使用 Kubernetes Python 异步客户端 AutoscalingV1Api 管理 HorizontalPodAutoscalerautoscaling/v1使用 Kubernetes Python 异步客户端 AutoscalingV1Api 管理 HorizontalPodAutoscalerautoscali后端云原生容器编排Kubernetes Python 异步客户端 AutoscalingV2Api 实战用 autoscaling/v2 管理 HPA 弹性伸缩Kubernetes Python 异步客户端 AutoscalingV2Api 实战用 autoscaling/v2 管理 HPA 弹性伸缩 本篇技术指南以后端云原生容器编排Kubernetes Python 异步客户端 NetworkingApi 使用指南基于 kubernetes.aio 的网络 API 组访问Kubernetes Python 异步客户端 NetworkingApi 使用指南基于 kubernetes.aio 的网络 API 组访问 导读 本文围绕后端云原生容器编排创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考