马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
利用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, Field
- class 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 方案优化建议
- Coordinate = Annotated[
- list[int],
- Field(min_length=2, max_length=2, example=[100, 400])
- ]
复制代码- class Point(BaseModel):
- x: int
- y: int
- class Line(BaseModel):
- start: Point
- end: Point
- class OptimizedVideoData(BaseModel):
- rtsp_video: str
- points: list[Point]
- passway: list[list[Line]]
复制代码 三、验证增强计谋
3.1 数值范围约束
- from pydantic import conint
- PixelCoordinate = Annotated[
- conint(ge=0, le=1920), # 假设最大分辨率1920x1080
- Field(description="像素坐标系坐标值")
- ]
复制代码 3.2 自定义验证器
- from pydantic import validator
- class EnhancedPoint(BaseModel):
- x: int
- y: int
- @validator('x', 'y')
- def check_coordinate_range(cls, v):
- if not (0 <= v <= 1920):
- raise ValueError("坐标值超出有效范围")
- return v
复制代码 四、最佳实践建议
- class DocumentedVideoData(BaseModel):
- """视频分析数据模型(带完整文档)"""
- rtsp_video: str = Field(
- ...,
- title="视频流地址",
- description="RTSP协议的视频流访问地址",
- example="rtsp://localhost:5555/live"
- )
复制代码- class Config:
- json_schema_extra = {
- "points_example": [[100, 400], [500, 400]],
- "passway_example": [[[500, 200], [100, 200]]]
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |