Monday 25 October 2021

Pydantic: constr: Constrain string values

‘constr’ type method is used to constraining str values. Below table summarizes the arguments of ‘constr’ method.

 

Argument

Data type

Description

strip_whitespace

bool = False

removes leading and trailing whitespace

to_lower

bool = False

turns all characters to lowercase

strict

bool = False

controls type coercion

min_length

int = None

minimum length of the string

max_length

int = None

maximum length of the string

curtail_length

int = None

shrinks the string length to the set value when it is longer than the set value

regex

str = None

regex to validate the string against

 

Example

class Box(BaseModel):
    id: int
    address: constr(to_lower=True)

 

Find the below working application.

 

constr_demo_1.py

 

from pydantic import (
    BaseModel,
    constr,
    ValidationError
)

class Box(BaseModel):
    id: int
    address: constr(to_lower=True)

try:
    box1 = Box(id = 1, address='BANAGALORE, Chodeswari street')
    print(box1.json())
except ValidationError as e:
    print(e.json())

 

Output

{"id": 1, "address": "banagalore, chodeswari street"}

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment