简体   繁体   中英

How to validate entries using Pydantic validator?

I am new to pydantic. What are some techniques I can use in Pydantic to sanitize my data and how to run proper validation checks on it? 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. If you change that, it passes validation.

Also, you must put assigning part in a try block.

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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