欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > 使用Pydantic优雅处理几何数据结构 - 前端输入验证实践

使用Pydantic优雅处理几何数据结构 - 前端输入验证实践

2025/4/22 20:19:43 来源:https://blog.csdn.net/qq_51116518/article/details/147342481  浏览:    关键词:使用Pydantic优雅处理几何数据结构 - 前端输入验证实践

使用Pydantic优雅处理几何数据结构 - 前端输入验证实践

一、应用场景解析

在视频分析类项目中,前端常需要传递几何坐标数据。例如智能安防系统中,需要接收:

  • 视频流地址(rtsp_video)
  • 检测区域坐标点(points)
  • 警戒通道坐标(passway)

这些数据需要满足严格的格式要求:

{"rtsp_video": "rtsp://localhost:5555/live","points": [[100, 400], [500, 400], [500, 200], [100, 200]],"passway": [[[500, 200], [100, 200]]]
}

二、基础模型设计

2.1 优化方案

from typing import Annotated
from pydantic import BaseModel, Fieldclass VideoData(BaseModel):"""视频分析基础数据模型"""rtsp_video: str = Field(example="rtsp://localhost:5555/live",description="RTSP视频流地址")points: list[Annotated[list[int], Field(min_length=2, max_length=2,example=[100, 400])]]passway: list[list[Annotated[list[int], Field(min_length=2,max_length=2,example=[[500, 200]])]]]

支持传入的json参考:

{
“rtsp_video”: “rtsp://localhost:5555/live”,
“points”:[[100, 400], [500, 400], [500, 200], [100, 200]],
“passway”: [[[500, 200], [100, 200]]]
}

2.2 方案优化建议

  1. 使用类型别名增强可读性
Coordinate = Annotated[list[int], Field(min_length=2, max_length=2, example=[100, 400])
]
  1. 基础结构化嵌套模型
class Point(BaseModel):x: inty: intclass Line(BaseModel):start: Pointend: Pointclass OptimizedVideoData(BaseModel):rtsp_video: strpoints: list[Point]passway: list[list[Line]]

三、验证增强策略

3.1 数值范围约束

from pydantic import conintPixelCoordinate = Annotated[conint(ge=0, le=1920),  # 假设最大分辨率1920x1080Field(description="像素坐标系坐标值")
]

3.2 自定义验证器

from pydantic import validatorclass EnhancedPoint(BaseModel):x: inty: int@validator('x', 'y')def check_coordinate_range(cls, v):if not (0 <= v <= 1920):raise ValueError("坐标值超出有效范围")return v

四、最佳实践建议

  1. 为字段添加文档注释
class DocumentedVideoData(BaseModel):"""视频分析数据模型(带完整文档)"""rtsp_video: str = Field(...,title="视频流地址",description="RTSP协议的视频流访问地址",example="rtsp://localhost:5555/live")
  1. 配置模型行为
class Config:json_schema_extra = {"points_example": [[100, 400], [500, 400]],"passway_example": [[[500, 200], [100, 200]]]}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词