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

打印 上一主题 下一主题

主题 1635|帖子 1635|积分 4905

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

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

一、应用场景解析

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


  • 视频流地址(rtsp_video)
  • 检测区域坐标点(points)
  • 警戒通道坐标(passway)
这些数据需要满足严格的格式要求:
  1. {
  2.     "rtsp_video": "rtsp://localhost:5555/live",
  3.     "points": [[100, 400], [500, 400], [500, 200], [100, 200]],
  4.     "passway": [[[500, 200], [100, 200]]]
  5. }
复制代码
二、基础模型设计

2.1 优化方案

  1. from typing import Annotated
  2. from pydantic import BaseModel, Field
  3. class VideoData(BaseModel):
  4.     """视频分析基础数据模型"""
  5.     rtsp_video: str = Field(
  6.         example="rtsp://localhost:5555/live",
  7.         description="RTSP视频流地址"
  8.     )
  9.    
  10.     points: list[Annotated[list[int], Field(
  11.         min_length=2,
  12.         max_length=2,
  13.         example=[100, 400]
  14.     )]]
  15.    
  16.     passway: list[list[Annotated[list[int], Field(
  17.         min_length=2,
  18.         max_length=2,
  19.         example=[[500, 200]]
  20.     )]]]
  21.    
复制代码
支持传入的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[
  2.     list[int],
  3.     Field(min_length=2, max_length=2, example=[100, 400])
  4. ]
复制代码

  • 基础结构化嵌套模型
  1. class Point(BaseModel):
  2.     x: int
  3.     y: int
  4. class Line(BaseModel):
  5.     start: Point
  6.     end: Point
  7. class OptimizedVideoData(BaseModel):
  8.     rtsp_video: str
  9.     points: list[Point]
  10.     passway: list[list[Line]]
复制代码
三、验证增强计谋

3.1 数值范围约束

  1. from pydantic import conint
  2. PixelCoordinate = Annotated[
  3.     conint(ge=0, le=1920),  # 假设最大分辨率1920x1080
  4.     Field(description="像素坐标系坐标值")
  5. ]
复制代码
3.2 自定义验证器

  1. from pydantic import validator
  2. class EnhancedPoint(BaseModel):
  3.     x: int
  4.     y: int
  5.     @validator('x', 'y')
  6.     def check_coordinate_range(cls, v):
  7.         if not (0 <= v <= 1920):
  8.             raise ValueError("坐标值超出有效范围")
  9.         return v
复制代码
四、最佳实践建议


  • 为字段添加文档解释
  1. class DocumentedVideoData(BaseModel):
  2.     """视频分析数据模型(带完整文档)"""
  3.     rtsp_video: str = Field(
  4.         ...,
  5.         title="视频流地址",
  6.         description="RTSP协议的视频流访问地址",
  7.         example="rtsp://localhost:5555/live"
  8.     )
复制代码

  • 设置模型行为
  1. class Config:
  2.     json_schema_extra = {
  3.         "points_example": [[100, 400], [500, 400]],
  4.         "passway_example": [[[500, 200], [100, 200]]]
  5.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表