Created
July 9, 2021 21:47
-
-
Save fletcheaston/91386b5b4f51228fcad4e9460e908c08 to your computer and use it in GitHub Desktop.
Helpful Pydantic classes that I use for FastAPI apps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import uuid | |
from datetime import datetime | |
from typing import Optional | |
from humps import camelize # This is from the pyhumps library (https://pypi.org/project/pyhumps/) | |
from pydantic import BaseModel as PydanticBase | |
class BaseModel(PydanticBase): | |
# Standard config settings. | |
class Config: | |
# Camelize will give us camelCase field names for external usage (docs, client-side app, etc.) | |
# while maintaining snake_case for internal usage. | |
alias_generator = camelize | |
# Allow internal usage of snake_case field names. | |
allow_population_by_field_name = True | |
# Extra whitespace? Gross. | |
anystr_strip_whitespace = True | |
# If not a standard or Pydantic type, just check `isinstance`. | |
arbitrary_types_allowed = True | |
# Allow FastAPI to auto-convert database objects to Pydantic objects. | |
orm_mode = True | |
# Private fields are cool. | |
underscore_attrs_are_private = True | |
# Just makes enum comparisons a bit cleaner. | |
# Allows for `if x == MyEnum.OPTION_A` instead of `if x == MyEnum.OPTION_A.value`. | |
use_enum_values = True | |
class SavedBaseModel(BaseModel): | |
# Every object from the database/cache/data-persistence-layer has these attributes. | |
id: uuid.UUID | |
created: datetime | |
updated: datetime | |
class BaseIdentifier(BaseModel): | |
# Potentially other ways to identify objects, but the UUID is standard. | |
id: Optional[uuid.UUID] = None | |
class BaseFilter(BaseModel): | |
page: int = 1 | |
per_page: int = 100 | |
# These properties make Django pagination easier, using slice notation on querysets. | |
@property | |
def start(self) -> int: | |
return (self.page - 1) * self.per_page | |
@property | |
def end(self) -> int: | |
return self.page * self.per_page | |
# These properties make SQLAlchemy pagination easier. | |
@property | |
def offset(self) -> int: | |
return (self.page - 1) * self.per_page | |
@property | |
def limit(self) -> int: | |
return self.per_page |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment