Roman Imankulov

Roman Imankulov

Full-stack Python web developer from Porto

search results (esc to close)

Pydantic

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
Roman Imankulov

Hey, I am Roman, and you can hire me.

I am a full-stack Python web developer who loves helping startups and small teams turn their ideas into products.

More about me and my skills