- 后端
- 云原生
- 容器编排
【免费下载链接】python
Official Python client library for kubernetes
本指南以 Kubernetes Python Client(asyncio 版)官方 API 参考文档为核心,系统讲解V1PersistentVolumeClaimSpec模型:它描述了一个 PersistentVolumeClaim(PVC)所要求的存储属性——包括访问模式、存储容量、StorageClass、卷模式、数据源与卷选择器等全部 9 个字段。阅读本文后,你将掌握该模型的字段语义、camelCase/snake_case 双别名序列化机制,以及如何结合CoreV1Api在异步代码中创建与读取 PVC。
模型定位:从 API 参考页到实际类定义
关联文档 doc/source/kubernetes.aio.client.models.v1_persistent_volume_claim_spec.rst 是 Sphinx 通过automodule指令自动生成的 API 参考页,它声明渲染kubernetes.aio.client.models.v1_persistent_volume_claim_spec模块的全部公开成员。该模块的核心类为V1PersistentVolumeClaimSpec,源码位于 kubernetes/aio/client/models/v1_persistent_volume_claim_spec.py,由 OpenAPI Generator 基于 Kubernetesrelease-1.37的 OpenAPI 规范生成。
类文档字符串对该模型的定位是:
PersistentVolumeClaimSpec describes the common attributes of storage devices and allows a Source for provider-specific attributes
即在 Kubernetes 对象模型中,V1PersistentVolumeClaimSpec描述存储设备的通用属性,并允许通过数据源(Source)引入提供方特有的属性。
从对象组合关系看,V1PersistentVolumeClaimSpec被两个上层模型引用:
- V1PersistentVolumeClaim 的
spec字段类型为可选的V1PersistentVolumeClaimSpec,这也是创建 PVC 时实际提交给 API Server 的声明部分; - V1PersistentVolumeClaimTemplate 的
spec字段为必填的V1PersistentVolumeClaimSpec,用于 StatefulSet 等控制器按模板动态生成 PVC。
模型在包导出层可见:kubernetes.aio.client.models的__init__.py(kubernetes/aio/client/models/init.py)以及kubernetes.aio.client的__init__.py(kubernetes/aio/client/init.py)均注册了V1PersistentVolumeClaimSpec,因此可以直接通过from kubernetes.aio.client import V1PersistentVolumeClaimSpec导入。
九个字段全景:属性、类型与语义
以下为模型定义的完整字段清单,Python 属性名、wire(JSON)名称、类型与说明均与 kubernetes/aio/docs/V1PersistentVolumeClaimSpec.md 及源码中的openapi_types/attribute_map一致:
| Python 属性 | wire 名称(JSON) | 类型 | 必填 | 语义 |
|---|---|---|---|---|
access_modes | accessModes | List[str] | 否 | 卷应具有的期望访问模式 |
data_source | dataSource | V1TypedLocalObjectReference | 否 | 同命名空间内被引用的数据源对象 |
data_source_ref | dataSourceRef | V1TypedObjectReference | 否 | 被引用的数据源对象(支持跨命名空间) |
resources | resources | V1VolumeResourceRequirements | 否 | 卷的存储资源请求与上限 |
selector | selector | V1LabelSelector | 否 | 绑定 PersistentVolume 的标签选择器 |
storage_class_name | storageClassName | str | 否 | 该声明所需的 StorageClass 名称 |
volume_attributes_class_name | volumeAttributesClassName | str | 否 | 声明使用的 VolumeAttributesClass 名称 |
volume_mode | volumeMode | str | 否 | 声明所需的卷类型 |
volume_name | volumeName | str | 否 | 支撑该声明的 PersistentVolume 绑定引用 |
下面逐个展开字段语义与使用要点。
accessModes:期望的访问模式
accessModes描述卷应具备的访问模式列表,声明方用它表达"该卷需要以哪些方式被节点访问"。常见的取值包括ReadWriteOnce、ReadOnlyMany、ReadWriteMany等(具体枚举由 Kubernetes API 定义,见源码字段描述中指向的访问模式说明)。该字段是可选的,通常与resources.requests.storage一起作为 PVC 声明中最核心的两个字段使用。
volumeMode:卷类型
volumeMode定义声明需要哪种类型的卷。源码字段描述特别强调:当声明未包含该字段时,隐含值为Filesystem;另一类典型取值是Block,表示裸块设备卷。也就是说,不显式设置volumeMode等价于请求文件系统型卷。
storageClassName:StorageClass 选择
storageClassName是声明所要求的 StorageClass 名称。它决定了集群中哪个存储类(以及对应的 Provisioner、回收策略、绑定模式等)来满足该声明。声明中省略该字段时,Kubernetes 会按集群默认 StorageClass 处理(若存在默认类)。
volumeAttributesClassName:可动态变更的卷属性类
volumeAttributesClassName用于指定该声明使用的 VolumeAttributesClass。源码字段描述(v1_persistent_volume_claim_spec.py#L116)给出了非常详细的行为约定:
- 若指定,CSI 驱动会按对应 VolumeAttributesClass 中定义的属性创建或更新卷;
- 它的用途与
storageClassName不同,可以在声明创建后被修改; - 空字符串或
None表示不对声明应用任何 VolumeAttributesClass; - 如果声明进入
Infeasible错误状态,可将该字段重置为其先前值(包括None)以取消修改; - 如果
volumeAttributesClass引用的资源不存在,该 PVC 会进入Pending状态,并通过modifyVolumeStatus字段反映,直到对应资源出现。
这是该模型在较新 Kubernetes 版本(含 VolumeAttributesClass 特性)中引入的字段,动态修改能力使其区别于创建后基本固定的storageClassName。
resources:存储容量请求
resources字段类型为V1VolumeResourceRequirements(见 v1_volume_resource_requirements.py),它包含两个键:
requests:Dict[str, str],描述所需的最小计算资源量,PVC 中通常填写storage(如"10Gi");limits:Dict[str, str],描述允许的最大资源量。
从源码注释看,requests省略时默认取limits的值(若显式指定),否则为实现定义值,且requests不能超过limits。对于 PVC 场景,最常见的是只设置requests中的storage。
selector:卷绑定选择器
selector字段类型为V1LabelSelector(见 v1_label_selector.py),用于在动态/静态供应时约束可绑定的 PersistentVolume:
matchLabels:Dict[str, str],键值对形式的精确匹配,等价于 operator 为In的表达式要求;matchExpressions:List[V1LabelSelectorRequirement],表达式列表,多个要求之间是 AND 关系。
matchLabels与matchExpressions的结果会做 AND 合并。需要说明的是,空的选择器匹配所有对象,而None选择器不匹配任何对象——这一语义差异在使用时需要留意。
dataSource 与 dataSourceRef:卷数据来源
这两个字段用于声明"从已有对象填充新卷"(例如从快照、克隆或已有 PVC 恢复):
data_source(dataSource)类型为V1TypedLocalObjectReference(见 v1_typed_local_object_reference.py),包含apiGroup、kind、name三个必填字段(kind与name为必填,apiGroup可选),用于定位同命名空间内的 typed 引用对象。当apiGroup未指定时,被引用的kind必须位于核心 API 组;第三方类型则必须提供apiGroup。data_source_ref(dataSourceRef)类型为V1TypedObjectReference(见 v1_typed_object_reference.py),除apiGroup、kind、name外还包含可选的namespace字段,从而支持跨命名空间的数据源引用。源码字段描述指出:指定namespace时,目标命名空间需要存在gateway.networking.k8s.io/ReferenceGrant对象以允许该命名空间所有者接受引用;此能力属于 Alpha 特性,需启用CrossNamespaceVolumeDataSourcefeature gate。
两者并存的原因在于:dataSource保留了对同命名空间引用的向后兼容语义,而dataSourceRef提供了更完整的跨命名空间能力。
volumeName:绑定引用
volumeName是绑定引用(binding reference),即支撑该声明的 PersistentVolume 名称。在动态供应场景下它通常由控制器写入(例如卷绑定完成后回填),声明方一般无需手动设置;在预绑定(pre-bind)场景下,声明方也可以显式指定一个已有的 PV 名称以强制绑定。
序列化机制:camelCase 与 snake_case 双别名
V1PersistentVolumeClaimSpec基于 pydantic 的BaseModel,其字段定义使用了validation_alias=AliasChoices(...)与serialization_alias=...(见 v1_persistent_volume_claim_spec.py#L110-L118),带来以下实用特性:
- 输入双兼容:如
access_modes字段声明为AliasChoices("accessModes", "access_modes"),意味着构造模型时无论传入 Kubernetes wire 风格的accessModes,还是 Python 风格的access_modes,都会被接受; - 输出规范化:
serialization_alias保证to_json()与to_dict(serialize=True)输出 wire 名称(如accessModes、storageClassName),可直接作为 API 请求体; - 内部归一化:
__preprocess_input_names(v1_persistent_volume_claim_spec.py#L144-L174)会把 snake_case 键(如access_modes、storage_class_name、volume_attributes_class_name)统一规整为 wire 名称后交给 pydantic 校验。
模型的model_config(v1_persistent_volume_claim_spec.py#L176-L182)设置了validate_by_name=True、validate_by_alias=True、validate_assignment=True与extra="forbid",含义分别是:允许按属性名与别名双重校验、赋值时即时校验、并拒绝未声明的多余字段(未知字段会触发校验错误),这保证了模型与 Kubernetes API 规范严格对齐。
构造与使用:创建 PVC 的完整链路
直接从 JSON 构造
官方 Markdown 文档(kubernetes/aio/docs/V1PersistentVolumeClaimSpec.md)给出了最简洁的用法——从 JSON 字符串或字典构造模型,并支持反向序列化:
from kubernetes.aio.client.models.v1_persistent_volume_claim_spec import V1PersistentVolumeClaimSpec # 从 JSON 字符串创建实例 json = '{"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "10Gi"}}}' v1_persistent_volume_claim_spec_instance = V1PersistentVolumeClaimSpec.from_json(json) # 打印 JSON 字符串表示 print(V1PersistentVolumeClaimSpec.to_json()) # 转成字典 v1_persistent_volume_claim_spec_dict = v1_persistent_volume_claim_spec_instance.to_dict() # 从字典创建实例 v1_persistent_volume_claim_spec_from_dict = V1PersistentVolumeClaimSpec.from_dict(v1_persistent_volume_claim_spec_dict)面向对象方式构造
更符合 Python 习惯的做法是直接传具名参数,两个命名风格均可:
from kubernetes.aio.client.models.v1_persistent_volume_claim_spec import V1PersistentVolumeClaimSpec from kubernetes.aio.client.models.v1_volume_resource_requirements import V1VolumeResourceRequirements spec = V1PersistentVolumeClaimSpec( access_modes=["ReadWriteOnce"], resources=V1VolumeResourceRequirements(requests={"storage": "10Gi"}), storage_class_name="standard", volume_mode="Filesystem", )结合 CoreV1Api 创建 PVC(asyncio)
V1PersistentVolumeClaimSpec最终要挂载到V1PersistentVolumeClaim的spec字段上提交给集群。asyncio 版CoreV1Api.create_namespaced_persistent_volume_claim(kubernetes/aio/client/api/core_v1_api.py#L16895-L16981)接收V1PersistentVolumeClaim作为body,典型用法如下:
import asyncio from kubernetes import config from kubernetes.aio.client import ApiClient, CoreV1Api from kubernetes.aio.client.models import ( V1PersistentVolumeClaim, V1PersistentVolumeClaimSpec, V1VolumeResourceRequirements, ) async def create_pvc(): config.load_kube_config() # 或使用 config.load_incluster_config() async with ApiClient() as api_client: api = CoreV1Api(api_client) spec = V1PersistentVolumeClaimSpec( access_modes=["ReadWriteOnce"], resources=V1VolumeResourceRequirements(requests={"storage": "10Gi"}), storage_class_name="standard", ) pvc = V1PersistentVolumeClaim( api_version="v1", kind="PersistentVolumeClaim", metadata={"name": "my-pvc", "namespace": "default"}, spec=spec, ) created = await api.create_namespaced_persistent_volume_claim( namespace="default", body=pvc ) print(created) asyncio.run(create_pvc())create_namespaced_persistent_volume_claim的响应映射中200/201/202均返回V1PersistentVolumeClaim,401返回空。接口还支持pretty、dry_run(如"All")、field_manager、field_validation(Ignore/Warn/Strict)等控制参数,其中dry_run可用于不落库的校验演练。
读取与列表接口
与 PVC 声明相关的异步接口还包括(均位于 kubernetes/aio/client/api/core_v1_api.py):
list_namespaced_persistent_volume_claim(#L39966):按命名空间列出 PVC;read_namespaced_persistent_volume_claim(#L60809):读取单个 PVC;read_namespaced_persistent_volume_claim_status(#L61109):读取 PVC 的status子资源。
这些接口在返回V1PersistentVolumeClaim时,会通过V1PersistentVolumeClaim.from_dict内部反序列化spec字段(v1_persistent_volume_claim.py#L261),从而还原为V1PersistentVolumeClaimSpec实例。
从源码结构看设计要点
综合模型源码,可以总结出以下几个值得在集成开发中注意的设计点:
- 严格模式:
extra="forbid"意味着任何未声明字段(如拼写错误的accessModes变体)都会在from_dict/from_json阶段被 pydantic 拒绝,这有助于尽早发现 API 版本漂移或拼写错误。 - 无状态嵌套转换:嵌套对象在反序列化时通过各自的
from_dict递归构建(见 v1_persistent_volume_claim_spec.py#L295-L305),在序列化时通过_to_openapi_value递归调用嵌套模型的to_dict,因此任意深度的模型都能正确往返。 None处理策略:__openapi_generator_modern_projection在输出时对未设置的字段(值为None)默认不写入 JSON,只有显式赋值的可空字段才会输出,避免向 API Server 发送冗余的null字段。- 易用性:
to_str()/__repr__提供可读的 pprint 输出,__eq__/__ne__基于to_dict()结果比较,便于在测试中直接断言两个 spec 是否等价。
参考资源
- 关联 API 参考页:doc/source/kubernetes.aio.client.models.v1_persistent_volume_claim_spec.rst
- 模型源码:kubernetes/aio/client/models/v1_persistent_volume_claim_spec.py
- 官方属性文档与示例:kubernetes/aio/docs/V1PersistentVolumeClaimSpec.md
- 宿主模型:v1_persistent_volume_claim.py、v1_persistent_volume_claim_template.py
- 嵌套模型:v1_volume_resource_requirements.py、v1_label_selector.py、v1_typed_local_object_reference.py、v1_typed_object_reference.py
- 异步客户端接口:kubernetes/aio/client/api/core_v1_api.py
- 后端
- 云原生
- 容器编排
【免费下载链接】python
Official Python client library for kubernetes
相关推荐
Kubernetes Python Client(asyncio)V1PodDisruptionBudgetStatus 模型全解析:PDB 状态字段与异步 API 实战
Kubernetes Python Client(asyncio)V1PodDisruptionBudgetStatus 模型全解析:PDB 状态字段与异步 A
后端云原生容器编排Kubernetes Python Client 中 V1ScaleIOVolumeSource 模型详解:字段、序列化机制与实战用法
Kubernetes Python Client 中 V1ScaleIOVolumeSource 模型详解:字段、序列化机制与实战用法 本文以 Kubernet
后端云原生容器编排Kubernetes Python 客户端 V1DeviceClaimConfiguration 详解:DRA 设备声明配置模型解析与实战
Kubernetes Python 客户端 V1DeviceClaimConfiguration 详解:DRA 设备声明配置模型解析与实战 本指南以 Kuber
后端云原生容器编排
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考