Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anatoly-scherbakov/edbf365ea4473ab8fb34b5faacf9fcff to your computer and use it in GitHub Desktop.
Save anatoly-scherbakov/edbf365ea4473ab8fb34b5faacf9fcff to your computer and use it in GitHub Desktop.
Cannot use a custom pydantic-aware class with FastAPI query Depends()
from enum import Enum
from typing import Optional, Generic, TypeVar, Set
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from pydantic.fields import ModelField
ContainerType = TypeVar('ContainerType')
class Color(str, Enum):
"""Cat colors."""
RED = 'red'
WHITE = 'white'
BLACK = 'black'
class CommaSeparated(Generic[ContainerType]):
"""Comma separated values of a container."""
@classmethod
def __get_validators__(cls):
"""Ensure pydantic compatibility."""
yield cls.validate
@classmethod
def validate(cls, raw_value: str, field: ModelField) -> ContainerType:
"""Validate the raw value."""
raise ValueError(
'I will write this validation later, too lazy right now :(',
)
class CatsQuery(BaseModel):
"""Query our cats herd."""
color__in: Optional[CommaSeparated[Set[Color]]] = None
app = FastAPI()
@app.get('/cats')
def list_cats(query: CatsQuery = Depends()):
"""Filter the herd of cats and list them."""
app.openapi()
'''
Error:
get_openapi_operation_request_body
body_schema, _, _ = field_schema(
../venv/lib/python3.8/site-packages/pydantic/schema.py:222: in field_schema
f_schema, f_definitions, f_nested_models = field_type_schema(
../venv/lib/python3.8/site-packages/pydantic/schema.py:475: in field_type_schema
assert field.shape == SHAPE_SINGLETON, field.shape
E AssertionError: 10
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment