Kubernetes Python 客户端 V1ResourceClaimTemplateList 模型详解:用官方库读取 ResourceClaimTemplate 列表
后端云原生容器编排【免费下载链接】pythonOfficial Python client library for kubernetes项目地址https://gitcode.com/gh_mirrors/python1/python点击查看免费下载导读本文围绕 Kubernetes 官方 Python 客户端本项目中异步客户端kubernetes.aio.client.models.v1_resource_claim_template_list模块所定义的V1ResourceClaimTemplateList模型展开。该模型对应 Kubernetesresource.k8s.io/v1API 组中的ResourceClaimTemplateList资源类型是动态资源分配Dynamic Resource Allocation体系下批量读取 ResourceClaimTemplate 对象的标准返回容器。读完本文你将掌握该模型的全部字段语义、与V1ResourceClaimTemplate/V1ListMeta的嵌套关系、JSON/Dict 双向序列化用法以及如何通过ResourceV1Api同步与ResourceV1Api异步 aio的 list 方法实际拿到并解析这种列表对象。一、模型定位ResourceClaimTemplateList 在 Kubernetes API 中的角色ResourceClaimTemplateList的官方定义是 a collection of claim templates一组 claim 模板的集合。在 Kubernetes 的 Dynamic Resource Allocation 机制中ResourceClaimTemplate用于批量声明可被 Pod 引用的资源请求模板而它的 List 形态——也就是本文的主角——是 API Server 在响应列出 ResourceClaimTemplate类请求时统一返回的容器类型。从本项目仓库中的 OpenAPI 定义kubernetes/swagger.json.unprocessed可以确认io.k8s.api.resource.v1.ResourceClaimTemplateList定义包含x-kubernetes-group-version-kind元数据group 为resource.k8s.ioversion 为v1kind 为ResourceClaimTemplateList。也就是说无论你是用同步客户端还是异步客户端当向/apis/resource.k8s.io/v1/namespaces/{namespace}/resourceclaimtemplates发起 GET 请求时响应体都会被解析成这个模型实例。仓库中同时存在v1、v1beta1、v1beta2三个版本的ResourceClaimTemplateList定义见 kubernetes/swagger.json.unprocessed 与 kubernetes/swagger.json.unprocessed说明该资源类型仍处于多版本并存演进阶段本项目为每个版本都生成了对应的 Python 模型类。二、模型类速览V1ResourceClaimTemplateList 的字段定义V1ResourceClaimTemplateList定义在 kubernetes/aio/client/models/v1_resource_claim_template_list.py是基于 pydanticBaseModel的数据类继承标准的 Kubernetes 列表资源约定kind/apiVersion/metadata 具体的items数组。字段一览如下字段类型是否必填说明api_versionOptional[str]否默认None对象的版本化 schema 标识服务端会把可识别的 schema 转换为最新的内部值对无法识别的值会拒绝。序列化到 wire 格式时使用 JSON 键apiVersionitemsList[V1ResourceClaimTemplate]是资源 claim 模板列表。OpenAPI 定义中required数组仅包含items这是全模型中唯一必填字段kindOptional[str]否默认NoneREST 资源类型标识CamelCase 风格创建后不可更新服务端可能根据请求端点自行推断metadataOptional[V1ListMeta]否默认None标准列表元数据如continue、resourceVersion、remainingItemCount等类型为V1ListMeta这三个可选字段加上必填的items与__properties中声明的 wire 字段集合[apiVersion, items, kind, metadata]完全对应。2.1 必填字段 items 及其元素类型items是模型的唯一必填字段元素类型为V1ResourceClaimTemplate。这个嵌套类定义在同目录的 kubernetes/aio/client/models/v1_resource_claim_template.py 中包含api_version、kind、metadata类型为V1ObjectMeta和spec类型为V1ResourceClaimTemplateSpec四个字段。也就是说V1ResourceClaimTemplateList的完整嵌套结构为V1ResourceClaimTemplateList ├── apiVersion: str ├── kind: str ├── metadata: V1ListMeta └── items: List[V1ResourceClaimTemplate] ├── apiVersion: str ├── kind: str ├── metadata: V1ObjectMeta └── spec: V1ResourceClaimTemplateSpec从源码的openapi_types类变量v1_resource_claim_template_list.py可以直观印证这一映射items: List[V1ResourceClaimTemplate]、metadata: V1ListMeta。V1ResourceClaimTemplate和V1ListMeta分别通过from kubernetes.aio.client.models.v1_resource_claim_template import V1ResourceClaimTemplate与from kubernetes.aio.client.models.v1_list_meta import V1ListMeta导入。2.2 字段别名机制api_version 与 apiVersion注意api_version字段在源码中的声明方式api_version: Optional[StrictStr] Field( defaultNone, validation_aliasAliasChoices(apiVersion, api_version), serialization_aliasapiVersion, ... )它同时接受apiVersionKubernetes wire 格式和api_versionPython 命名风格作为输入别名但序列化时一律输出为apiVersion。from_dict中还会先经过__preprocess_input_names做归一化处理当输入 dict 只有api_version而没有apiVersion时会自动补齐apiVersion键见 v1_resource_claim_template_list.py。这意味着从 JSON 响应反序列化时你无需手动转换键名。三、模型的核心方法JSON 与 Dict 双向转换与仓库中所有由 OpenAPI Generator 生成的模型一致V1ResourceClaimTemplateList提供了一套完整的序列化方法官方示例见 kubernetes/docs/V1ResourceClaimTemplateList.mdfrom kubernetes.aio.client.models.v1_resource_claim_template_list import V1ResourceClaimTemplateList # 从 JSON 字符串创建实例 json {} instance V1ResourceClaimTemplateList.from_json(json) # 打印 JSON 字符串表示 print(V1ResourceClaimTemplateList.to_json()) # 转换为 dict d instance.to_dict() # 从 dict 再创建实例可用于回程转换 instance2 V1ResourceClaimTemplateList.from_dict(d)各方法的实现要点均可从 v1_resource_claim_template_list.py 源码确认from_json(json_str)内部直接json.loads(json_str)后委托给from_dictfrom_dict(obj)先做别名归一化再通过cls.model_validate(...)构造实例对items列表中的每个元素调用V1ResourceClaimTemplate.from_dict(_item)对metadata调用V1ListMeta.from_dict(...)实现递归反序列化to_dict(serializeFalse)返回全部声明字段的 dict默认使用 Python 风格键api_versionserializeTrue时使用 wire 键apiVersionto_json()基于 alias 输出 JSON内部经由__openapi_generator_modern_projection投影方法只输出非None字段exclude_noneTrue且对items和metadata递归调用各自的to_dict()以保证嵌套对象也被正确序列化。此外模型还实现了__eq__/__ne__基于to_dict()结果比较和to_str/__repr__基于pprint.pformat方便调试时直接print(list_obj)。四、实战通过 ResourceV1Api 获取并解析列表V1ResourceClaimTemplateList不会凭空构造它主要由ResourceV1Api的列表接口作为返回值出现。在 kubernetes/aio/client/api/resource_v1_api.py 中异步客户端提供两个相关方法list_namespaced_resource_claim_template(namespace, ...)列出指定命名空间下的 ResourceClaimTemplate返回类型注解即为V1ResourceClaimTemplateList源码第 8103 行对应的 HTTP 路径为GET /apis/resource.k8s.io/v1/namespaces/{namespace}/resourceclaimtemplateslist_resource_claim_template_for_all_namespaces(...)跨全部命名空间列出源码第 9011 行同样返回V1ResourceClaimTemplateList。4.1 同步客户端调用示例以仓库文档 kubernetes/docs/ResourceV1Api.md 中的完整示例为骨架整理出最小可运行版本import os import kubernetes.client from kubernetes.client.rest import ApiException from pprint import pprint configuration kubernetes.client.Configuration(hosthttp://localhost) configuration.api_key[BearerToken] os.environ[API_KEY] with kubernetes.client.ApiClient(configuration) as api_client: api_instance kubernetes.client.ResourceV1Api(api_client) namespace default try: api_response api_instance.list_namespaced_resource_claim_template( namespacenamespace, prettytrue, label_selectorappexample, ) pprint(api_response) # api_response 即为 V1ResourceClaimTemplateList 实例 print(模板数量:, len(api_response.items)) for tpl in api_response.items: print(tpl.metadata.name, tpl.spec) except ApiException as e: print(调用失败: %s\n % e)4.2 异步asyncio客户端调用示例本仓库同时维护了异步客户端kubernetes.aio模块结构见 kubernetes/aio/README.md。异步版本只需把ApiClient放进async with上下文并await对应方法import os import asyncio import kubernetes.aio.client from kubernetes.aio.client.rest import ApiException async def main(): configuration kubernetes.aio.client.Configuration(hosthttp://localhost) configuration.api_key[BearerToken] os.environ[API_KEY] async with kubernetes.aio.client.ApiClient(configuration) as api_client: api_instance kubernetes.aio.client.ResourceV1Api(api_client) try: resp await api_instance.list_namespaced_resource_claim_template( namespacedefault, limit100, ) print(total items:, len(resp.items)) for item in resp.items: print(item.metadata.name, item.metadata.creation_timestamp) except ApiException as e: print(Exception: %s\n % e) asyncio.run(main())异步版本的返回类型同样为V1ResourceClaimTemplateList见 resource_v1_api.py 的返回注解与_response_types_map中200: V1ResourceClaimTemplateList的映射这意味着上文的items/metadata/to_dict()等全部 API 在两种客户端下完全一致。4.3 list 接口关键参数说明以list_namespaced_resource_claim_template为例除必填的namespace外常用的可选参数完整参数表见 ResourceV1Api.md参数类型作用与注意事项label_selector/field_selectorstr分别按标签、字段过滤返回对象默认返回全部limitint单次最多返回的条目数若还有更多条目服务端会在 list 元数据里设置continue令牌_continuestr分页续传令牌只能用于与首次请求完全相同的查询参数令牌过期一般 5~15 分钟或服务端配置变更时会返回 410需要重新发起不带continue的列表请求resource_versionstr对请求可被服务的资源版本设置约束默认不设置resource_version_matchstr配合resource_version使用官方建议在设置 resourceVersion 的列表调用中一并设置watchbool设为true时转为 watch 流式监听此时不支持continue需配合resource_versionallow_watch_bookmarksbool请求类型为BOOKMARK的 watch 事件非 watch 时忽略send_initial_eventsbool与watchtrue搭配时先发送合成事件反映集合当前状态再进入增量流启用时要求同时设置resource_version_matchtimeout_secondsintlist/watch 调用的整体超时与请求是否活跃无关prettystrtrue时输出美化格式默认由 user-agent 决定4.4 分页读取完整列表的推荐写法由于limit与continue的组合是服务端保证的一致性快照分页单次 list 后发生的增删改不会混入后续分页结果推荐按如下模式遍历全部模板continue_token None while True: resp await api_instance.list_namespaced_resource_claim_template( namespacedefault, limit50, _continuecontinue_token, ) for item in resp.items: process(item) continue_token resp.metadata.continue_ # V1ListMeta.continue_ 字段 if not continue_token: break注意V1ListMeta中continue字段对应的 Python 属性名为continue_尾部带下划线以避开 Python 关键字。五、源码级实现细节pydantic 模型的行为约束理解模型的底层行为有助于规避使用陷阱以下是 v1_resource_claim_template_list.py 中model_config的关键配置validate_by_nameTrue与validate_by_aliasTrue既可按字段名如api_version也可按别名如apiVersion传参校验validate_assignmentTrue实例化后给字段重新赋值时同样触发校验extraforbid禁止传入未声明字段。若你手动构造实例时误传了spec、itemsX等未知键pydantic 会直接抛出校验异常而不是静默忽略这在调试接口数据不匹配时非常有帮助protected_namespaces()允许model_validate等 pydantic 保留名作为普通字段使用。另外需要留意一个坑items字段名与 pydantic 的实例属性体系没有任何冲突可以直接通过obj.items访问而真正的序列化路径__openapi_generator_modern_projection会对items中每个元素调用_to_openapi_value递归转换保证嵌套模型V1ResourceClaimTemplate也被正确展开成 dict/JSON而非只输出其 pydantic 内部表示。仓库模型文件顶部的_to_legacy_value/_to_openapi_value/_get_openapi_to_dict辅助函数v1_resource_claim_template_list.py就是为这套新旧两代序列化约定兼容而设计的。六、模型校验的测试与使用注意事项虽然本模型主要用于读场景仍建议关注以下实践要点必填字段校验items是唯一必填字段。从 API Server 正常返回的列表响应必然包含该字段如果手动from_dict构造且缺失itemspydantic 会抛出ValidationError。必要时可用items[]表示空列表。版本适配本项目基于 OpenAPIrelease-1.37生成见 v1_resource_claim_template_list.py。若你的集群版本较老或较新字段集合可能略有差异仓库同步维护了v1beta1、v1beta2版本的同名模型类kubernetes/aio/client/models/ 目录下v1beta1_resource_claim_template_list.py、v1beta2_resource_claim_template_list.py跨版本迁移时应选择与集群 API 组启用状态匹配的类。别名输入宽容得益于AliasChoices(apiVersion, api_version)与__preprocess_input_names直接V1ResourceClaimTemplateList(**{apiVersion: resource.k8s.io/v1, items: [], kind: ResourceClaimTemplateList})或使用api_version键均可正常解析。调试输出str(list_obj)/repr(list_obj)会以 pprint 格式输出完整嵌套结构便于在捕获到ApiException后快速核对响应内容。七、延伸阅读模型参考文档kubernetes/docs/V1ResourceClaimTemplateList.md、kubernetes/aio/docs/V1ResourceClaimTemplateList.md模型源码kubernetes/aio/client/models/v1_resource_claim_template_list.py同步版位于 kubernetes/client/models/v1_resource_claim_template_list.py列表接口文档kubernetes/docs/ResourceV1Api.md 与异步 API 源码 kubernetes/aio/client/api/resource_v1_api.pyOpenAPI 原始定义kubernetes/swagger.json.unprocessed异步客户端安装与入门kubernetes/aio/README.md赞分享后端云原生容器编排【免费下载链接】pythonOfficial Python client library for kubernetes项目地址https://gitcode.com/gh_mirrors/python1/python点击查看免费下载相关推荐Kubernetes Python 客户端 V1DeploymentCondition 模型详解读取 Deployment 状态条件Kubernetes Python 客户端 V1DeploymentCondition 模型详解读取 Deployment 状态条件 导读 V1Deploym后端云原生容器编排Kubernetes Python 客户端详解V1DaemonSetStatus 模型字段、序列化与 DaemonSet 状态读取实战Kubernetes Python 客户端详解V1DaemonSetStatus 模型字段、序列化与 DaemonSet 状态读取实战 导读 V1Daemon后端云原生容器编排Kubernetes Python 客户端 V1APIGroupList 模型详解解析 /apis 端点返回的 API 组列表Kubernetes Python 客户端 V1APIGroupList 模型详解解析 /apis 端点返回的 API 组列表 Kubernetes 官方 P后端云原生容器编排上一篇终极指南如何用AI快速制作双语电子书轻松阅读全球名著下一篇pihole-regex进阶技巧如何添加Facebook、国际域名等专项过滤规则创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考