当前位置: 首页 > news >正文

使用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]]]}

相关文章:

  • MCP系列之架构篇:深入理解MCP的设计架构
  • 自定义 el-menu
  • 计算机网络——应用层
  • 基于SpringBoot成绩管理系统设计与实现(源码+文档+部署讲解)
  • STM32 基本GPIO控制
  • 鸿蒙NEXT开发键盘工具类(ArkTs)
  • 基于linux 设置无线网卡Monitor模式 sniffer抓包
  • C++面向对象
  • PyTorch入门------卷积神经网络
  • 医院数据中心智能化数据上报与调数机制设计
  • 2025mathorcup妈妈杯数学建模挑战赛C题:汽车风阻预测,详细思路,模型,代码更新中
  • 汽车免拆诊断案例 | 2019款大众途观L车鼓风机偶尔不工作
  • 零基础上手Python数据分析 (17):[案例实战] 电商销售数据分析 - 从数据到洞察的全流程演练
  • 磁流变式汽车减振器创新设计与关键技术研究
  • 【C++指南】哈希驱动的封装:如何让unordered_map/set飞得更快更稳?【上】
  • FreeRTOS菜鸟入门(七)·创建任务·静态任务创建
  • 网页端调用本地应用打开本地文件(PDF、Word、excel、PPT)
  • 再读bert(Bidirectional Encoder Representations from Transformers)
  • 动手学深度学习:手语视频在NiN模型中的测试
  • 万物互联时代,AWS IoT Core如何构建企业级物联网中枢平台?
  • 摩根士丹利基金雷志勇:AI带来的产业演进仍在继续,看好三大景气领域
  • 广汽集团一季度净亏损7.3亿元,同比转亏,总销量下滑9%
  • 可移动可变形的新型超材料问世
  • 建设高标准农田主要目标是什么?有哪些安排?两部门有关负责人答问
  • 董明珠的接班人还是董明珠
  • 主动权益基金一季度重仓股出炉:腾讯跃升至第一,阿里、比亚迪、中芯国际新进前十