Python:使用pydantic库进行数据校验

更新时间:2023-08-11 06:06:53 阅读: 评论:0

Python:使⽤pydantic库进⾏数据校验安装
pip install pydantic
⽰例
# -*- coding: utf-8 -*-
from datetime import datetime, date
from pathlib import Path
from typing import List, Optional
from pydantic import BaModel, ValidationError, constr
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
declarative import declarative_ba
def print_color(text):
"""PyCharm控制台打印带颜⾊的⽂字"""
print(f"\033[31m===== {text} =====\033[0m")
1、基本使⽤
class Ur(BaModel):
id:int# ⽆默认值,必填字段
name ='John Doe'# 有默认值,选填字段
signup_ts: Optional[datetime]=None# 选填字段
friends: List[int]=[]# 列表中的元素是int类型或者是可以转换成int类型的其他类型
external_data ={
'id':'123',
'signup_ts':'2017-06-01 12:22',
'friends':[1,'2', b'3']
}
ur = Ur(**external_data)
print(ur)
长脸适合什么发型
# > Ur id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
print(ur.id)
# > 123
2、错误校验
error_data ={
'id':'a123',
'signup_ts':'2017-06-01 12:22',
'friends':[1,'2','3']
}
try:
Ur(**error_data)
except ValidationError as e:
print(e.json())
"""
[
{
"loc": [
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
restroom]
"""
3、模型类的属性和⽅法
# 实例⽅法
print(ur.dict())
print(ur.json())
py())# 浅拷贝
print(ur.schema())
print(ur.schema_json())
"""
{'id': 123, 'signup_ts': datetime.datetime(2017, 6, 1, 12, 22), 'friends': [1, 2, 3], 'name': 'John Doe'} {"id": 123, "signup_ts": "2017-06-01T12:22:00", "friends": [1, 2, 3], "name": "John Doe"}
id=123 signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] name='John Doe'
{
'title': 'Ur',
'type': 'object',
'properties': {
'id': {
'title': 'Id',
'type': 'integer'
},
'signup_ts': {
'title': 'Signup Ts',
'type': 'string',
'format': 'date-time'
},
'friends': {
'title': 'Friends',
'default': [],
'type': 'array',
'items': {'type': 'integer'}狗屎英语
},
'name': {
lgbt法案是什么意思最好听的英文名'title': 'Name',
'default': 'John Doe',
'type': 'string'
}
流氓的英文
},
'required': ['id']
}
{
"title": "Ur",
"type": "object",
"properties": {
"id": {"title": "Id", "type": "integer"},
"signup_ts": {"title": "Signup Ts", "type": "string", "format": "date-time"},
"friends": {"title": "Friends", "default": [], "type": "array", "items": {"type": "integer"}},
"name": {"title": "Name", "default": "John Doe", "type": "string"}},
"required": ["id"]
}
}
"""
# 类⽅法
2013年职称英语考试用书print(Ur.par_obj(external_data))
print(Ur.par_raw('{"id": 123, "signup_ts": "2017-06-01T12:22:00", "friends": [1, 2, 3], "name": "John Doe"}'))
path = Path("obj.json")
path.write_text('{"id": 123, "signup_ts": "2017-06-01T12:22:00", "friends": [1, 2, 3], "name": "John Doe"}')
print(Ur.par_file(path))
"""
id=123 signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] name='John Doe'
id=123 signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] name='John Doe'
id=123 signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] name='John Doe'
"""
# 不进⾏数据校验
struct(path))
"""
signup_ts=None friends=[] name='John Doe'
"""
# 字段
bops
print(Ur.__fields__.keys())
"""
dict_keys(['id', 'signup_ts', 'friends', 'name'])
"""
4、递归模型
class Sound(BaModel):
sound:str
class Dog(BaModel):
name:str
birthday: date =None
sound: List[Sound]
dog = Dog(name="Tom", day(), sound=[{'sound':'wangwang'},{'sound':'miaomiao'}])
print(dog.dict())
"""
{
'name': 'Tom',
'birthday': datetime.date(2021, 2, 14),
'sound': [{'sound': 'wangwang'}, {'sound': 'miaomiao'}]
strive什么意思
}
"""
5、ORM模型
Ba = declarative_ba()
class CompanyOrm(Ba):
__tablename__ ='companies'
id= Column(Integer, primary_key=True, nullable=True)
public_key = Column(String(20), index=True, nullable=True, unique=True)    name = Column(String(63), unique=True)
domains = Column(ARRAY(String(255)))
class CompanyMode(BaModel):
id:int
public_key: constr(max_length=20)
name: constr(max_length=63)
domains: List[constr(max_length=255)]
class Config:
orm_mode =True
company_orm = CompanyOrm(
id=123,
public_key='foo_key',
name='Testing',
domains=['','']
)
print(CompanyMode.from_orm(company_orm))
"""
id=123 public_key='foo_key' name='Testing' domains=['', ''] """2010tvb颁奖典礼

本文发布于:2023-08-11 06:06:53,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/193520.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:校验   模型   类型
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图