简体   繁体   English

如何使用 Pydantic 验证器验证条目?

[英]How to validate entries using Pydantic validator?

I am new to pydantic.我是pydantic的新手。 What are some techniques I can use in Pydantic to sanitize my data and how to run proper validation checks on it?我可以在 Pydantic 中使用哪些技术来清理我的数据以及如何对其运行适当的验证检查? Can you please review my code and identify any errors in my code?你能检查一下我的代码并找出我的代码中的任何错误吗?

from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from pydantic import ValidationError, validator
import json

class UserModel(BaseModel):
    name: str
    age: int
    streetadr: str

    @validator('name')
    def name_must_contain_space(cls, v):
         names = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', " "]
         for x in v:
            if x not in names:
              raise ValueError('must contain letters')
         return v.title()

    @validator('age')
    def age_digits(cls, v):
        if not (int(v)):
            raise AttributeError("Must be a int")
        return v
    
    @validator('streetadr')
    def street_address(cls, v):
        if '' not in v and not v.isalnum():
            raise ValueError("Must be Alphanumric")
        return v 
class GroupModel(BaseModel):
    users: UserModel

u = GroupModel(users={'name':"james Wash", 'age':"23", 'streetadr':'2333 Sabrina Dr'})
print(u.json())

code quality is better.代码质量更好。 One possible mistake in group model:组模型中一个可能的错误:

class GroupModel(BaseModel):
    users: UserModel

should be应该

class GroupModel(BaseModel):
    users: List[UserModel]

Then for simplicity I rewrote following section.然后为了简单起见,我重写了以下部分。

a = {'name':"james1 Wash", 'age':"23", 'streetadr':'2333 Sabrina Dr'}
b = {'name':"hh axx", 'age':"32", 'streetadr':'2333 Dr'}

u = GroupModel(users=[a, b])

This wont pass validation test for var 'a' as name contains a number.这不会通过 var 'a' 的验证测试,因为 name 包含一个数字。 If you change that, it passes validation.如果您更改它,它将通过验证。

Also, you must put assigning part in a try block.此外,您必须将分配部分放在 try 块中。

try:
    u = GroupModel(users=[a, b])
except ValidationError as e:
    print(e) #to see details of error. Print only if you need to see it.

Look into error handling provided in pydantic.查看 pydantic 中提供的错误处理。 https://pydantic-docs.helpmanual.io/usage/models/#error-handling https://pydantic-docs.helpmanual.io/usage/models/#error-handling

There are many well written examples given there.那里给出了许多写得很好的例子。 You are making good progress.你正在取得良好的进展。

Pydantic simplifies validation. Pydantic 简化了验证。 You don't need to use it if you just need some simple validation logic.如果您只需要一些简单的验证逻辑,则不需要使用它。 But its better to use it in most real world projects were we need a lot of validation in many data classes and locations.但是最好在大多数现实世界的项目中使用它,因为我们需要在许多数据类和位置进行大量验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM