You can control the Pydantic behavior by providing Config class to a model or pydantic data class.
Below table summarizes all the possible options.
Option |
Description |
title |
the title for the generated JSON Schema |
anystr_strip_whitespace |
whether to strip leading and trailing whitespace for str & byte types (default: False) |
anystr_lower |
whether to make all characters lowercase for str & byte types (default: False) |
min_anystr_length |
the min length for str & byte types (default: 0) |
max_anystr_length |
the max length for str & byte types (default: 2 ** 16) |
validate_all |
whether to validate field defaults (default: False) |
extra |
whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore', 'allow', or 'forbid', or values of the Extra enum (default: Extra.ignore). 'forbid' will cause validation to fail if extra attributes are included, 'ignore' will silently ignore any extra attributes, and 'allow' will assign the attributes to the model. |
allow_mutation |
whether or not models are faux-immutable, i.e. whether __setattr__ is allowed (default: True) |
use_enum_values |
whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False) |
fields |
a dict containing schema information for each field; this is equivalent to using the Field class (default: None) |
validate_assignment |
whether to perform validation on assignment to attributes (default: False) |
allow_population_by_field_name |
whether an aliased field may be populated by its name as given by the model attribute, as well as the alias (default: False) |
error_msg_templates |
a dict used to override the default error message templates. Pass in a dictionary with keys matching the error messages you want to override (default: {}) |
arbitrary_types_allowed |
whether to allow arbitrary user types for fields (they are validated simply by checking if the value is an instance of the type). If False, RuntimeError will be raised on model declaration (default: False). See an example in Field Types. |
orm_mode |
whether to allow usage of ORM mode |
getter_dict |
a custom class (which should inherit from GetterDict) to use when decomposing ORM classes for validation, for use with orm_mode |
alias_generator |
a callable that takes a field name and returns an alias for it |
keep_untouched |
a tuple of types (e.g. descriptors) for a model's default values that should not be changed during model creation and will not be included in the model schemas. Note: this means that attributes on the model with defaults of this type, not annotations of this type, will be left alone. |
schema_extra |
a dict used to extend/update the generated JSON Schema, or a callable to post-process it; see schema customization. |
json_loads |
a custom function for decoding JSON; see custom JSON (de)serialisation |
json_dumps |
a custom function for encoding JSON; see custom JSON (de)serialisation |
json_encoders |
a dict used to customise the way types are encoded to JSON; see JSON Serialisation |
Example 1: Using json_encoders.
json_customize_serialization.py
from pydantic import BaseModel, ValidationError
from datetime import datetime
class Employee(BaseModel):
id: int
name: str
age: int
dateOfBirth: datetime
class Config:
json_encoders = {
datetime: lambda v: v.timestamp()
}
emp1 = Employee(id = 1, name = 'Ptr', age = 23, dateOfBirth = datetime(1988, 6, 6, 12, 13, 14))
emp1Json = emp1.json()
print('emp1Json -> ' + emp1Json)
Output
emp1Json -> {"id": 1, "name": "Ptr", "age": 23, "dateOfBirth": 581582594.0}
Example 2: Using orm_mode.
from_orm_1.py
from typing import List
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, constr
Base = declarative_base()
class EmployeeOrm(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True, nullable=False)
name = Column(String(63), unique=True)
age = Column(Integer, nullable=False)
class EmployeeModel(BaseModel):
id: int
name: constr(max_length=63)
age: int
class Config:
orm_mode = True
empOrm = EmployeeOrm(
id=123,
name='Krishna',
age=31
)
print('empOrm -> ' + str(empOrm))
empModel = EmployeeModel.from_orm(empOrm)
print('empModel -> ' + str(empModel))
Output
empOrm -> <__main__.EmployeeOrm object at 0x1083af670> empModel -> id=123 name='Krishna' age=31
Example 3: Using error_msg_templates and max_anystr_length
error_message_template_1.py
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
name: str
class Config:
max_anystr_length = 9
error_msg_templates = {
'value_error.any_str.max_length': 'max_length:{limit_value}',
}
try:
Model(name='krishna12345678')
except ValidationError as e:
print(e)
Output
1 validation error for Model name max_length:9 (type=value_error.any_str.max_length; limit_value=9)
Example 4: Define immutable classes
By setting 'allow_mutation' to False, we can define immutable models.
immutable_models.py
from pydantic import BaseModel
class Employee(BaseModel):
id: int
name: str
age: int
class Config:
allow_mutation = False
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
print('updating employee name')
emp1.name = 'Ram'
Output
Traceback (most recent call last): File "/Users/krishna/pydantic/immutable_models.py", line 14, in <module> emp1.name = 'Ram' File "pydantic/main.py", line 424, in pydantic.main.BaseModel.__setattr__ TypeError: "Employee" is immutable and does not support item assignment
No comments:
Post a Comment