Monday 25 October 2021

Pydantic: conbytes: Constrain bytes

‘conbytes’ method is used to constrain bytes. Below table summarizes the arguments of ‘conbytes’ method.

 

Argument

Data type

Description

strip_whitespace

bool = False

removes leading and trailing whitespace

to_lower

bool = False

turns all characters to lowercase

min_length

int = None

minimum length of the byte string

max_length

int = None

maximum length of the byte string

 

Example

class Box(BaseModel):
    id: int
    address: conbytes(to_lower=True, strip_whitespace = True)

 

Find the below working application.

 

conbytes_demo_1.py

 

from pydantic import (
    BaseModel,
    conbytes,
    ValidationError
)

class Box(BaseModel):
    id: int
    address: conbytes(to_lower=True, strip_whitespace = 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