Python中的ValidationError()及其常见错误类型解析
在Python中,ValidationError()是一个常见错误类型,它用于表示验证数据时出现的错误。当数据的某些方面不满足特定的验证规则时,ValidationError()将被触发。
常见错误类型包括:
1. MissingFieldError:表示缺少了一个或多个必需的字段。
from pydantic import BaseModel, ValidationError
class Person(BaseModel):
name: str
age: int
try:
person = Person()
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: MissingFieldError ['name'] field required
2. NonPositiveError:表示数值不是正数。
from pydantic import BaseModel, ValidationError
class Number(BaseModel):
value: int
try:
number = Number(value=-5)
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: NonPositiveError ['value'] ensure this value is greater than 0
3. MaxValueError: 表示数值超过了最大值。
from pydantic import BaseModel, ValidationError
class Number(BaseModel):
value: float
try:
number = Number(value=10.5)
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: MaxValueError ['value'] ensure this value is less than or equal to 10.0
4. StringMaxError:表示字符串的长度超过了最大限制。
from pydantic import BaseModel, ValidationError
class Text(BaseModel):
content: str
try:
text = Text(content="This is a very long string.")
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: StringMaxError ['content'] ensure this value has at most 10 characters
5. DictMaxError:表示字典中的键值对数量超过了最大限制。
from pydantic import BaseModel, ValidationError
class Info(BaseModel):
data: dict
try:
info = Info(data={"name": "John", "age": 25, "country": "USA"})
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: DictMaxError ['data'] ensure this value has at most 2 items
6. UrlError:表示URL格式错误。
from pydantic import BaseModel, ValidationError
class Website(BaseModel):
url: str
try:
website = Website(url="www.example.com")
except ValidationError as e:
for error in e.errors():
print(error["type"], error["loc"], error["msg"])
输出: UrlError ['url'] invalid or missing URL scheme
以上是一些常见的ValidationError()的错误类型,可以根据具体的需求和验证规则定义自己的模型类,并利用这些错误类型进行验证。它们可以帮助我们更容易地捕捉和处理特定的验证错误。
