Pydantic
table of contents
Project-specific models
See Pydantic model options for more options.
from pydantic import BaseModel
class Model(BaseModel):
"""Generic project-specific model."""
class Config:
# Allow field population by its name or alias
# (helpful for mapping external API values)
allow_population_by_field_name = True
class FrozenModel(BaseModel):
"""Generic project-specific frozen model."""
class Config:
# Make it frozen to allow using as dict keys
frozen = True
# Allow field population by its name or alias
# (helpful for mapping external API values)
allow_population_by_field_name = True
Integration with Arrow
import arrow
class PyArrow(arrow.Arrow):
"""FastAPI-serializable arrow instance."""
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
if v is None:
raise ValueError("Invalid value")
return arrow.get(v)
@classmethod
def __modify_schema__(cls, field_schema):
field_schema.update(type="string")
FastAPI models
We want to return models with camelCase
attributes, and we can automate it with Pydantic.
from pydantic import BaseModel
def to_camel_case(field_name: str) -> str:
"""Convert field name to camelCase."""
ret = "".join(word.capitalize() for word in field_name.split("_"))
return ret[0].lower() + ret[1:]
class ResponseModel(BaseModel):
class Config:
alias_generator = to_camel_case
allow_population_by_field_name = True
orm_mode = True