| 1 |
from typing import ( |
| 2 |
TYPE_CHECKING, |
| 3 |
Any, |
| 4 |
Dict, |
| 5 |
Generic, |
| 6 |
Optional, |
| 7 |
Type, |
| 8 |
TypeVar, |
| 9 |
) |
| 10 |
|
| 11 |
from pydantic import BaseModel |
| 12 |
from pydantic_core import core_schema |
| 13 |
|
| 14 |
from ninja import Body |
| 15 |
from ninja.orm import ModelSchema |
| 16 |
from ninja.schema import Schema |
| 17 |
from ninja.utils import is_optional_type |
| 18 |
|
| 19 |
|
| 20 |
class ModelToDict(dict): |
| 21 |
_wrapped_model: Any = None |
| 22 |
_wrapped_model_dump_params: Dict[str, Any] = {} |
| 23 |
|
| 24 |
@classmethod |
| 25 |
def __get_pydantic_core_schema__(cls, _source: Any, _handler: Any) -> Any: |
| 26 |
return core_schema.no_info_after_validator_function( |
| 27 |
cls._validate, |
| 28 |
cls._wrapped_model.__pydantic_core_schema__, |
| 29 |
) |
| 30 |
|
| 31 |
@classmethod |
| 32 |
def _validate(cls, input_value: Any) -> Any: |
| 33 |
return input_value.model_dump(**cls._wrapped_model_dump_params) |
| 34 |
|
| 35 |
|
| 36 |
def get_schema_annotations(schema_cls: Type[Any]) -> Dict[str, Any]: |
| 37 |
annotations: Dict[str, Any] = {} |
| 38 |
excluded_bases = {Schema, ModelSchema, BaseModel} |
| 39 |
bases = schema_cls.mro()[:-1] |
| 40 |
final_bases = reversed([b for b in bases if b not in excluded_bases]) |
| 41 |
|
| 42 |
for base in final_bases: |
| 43 |
annotations.update(getattr(base, "__annotations__", {})) |
| 44 |
|
| 45 |
return annotations |
| 46 |
|
| 47 |
|
| 48 |
def create_patch_schema(schema_cls: Type[Any]) -> Type[ModelToDict]: |
| 49 |
schema_annotations = get_schema_annotations(schema_cls) |
| 50 |
values, annotations = {}, {} |
| 51 |
|
| 52 |
for f in schema_cls.model_fields.keys(): |
| 53 |
t = schema_annotations[f] |
| 54 |
if not is_optional_type(t): |
| 55 |
values[f] = getattr(schema_cls, f, None) |
| 56 |
annotations[f] = Optional[t] |
| 57 |
values["__annotations__"] = annotations |
| 58 |
OptionalSchema = type(f"{schema_cls.__name__}Patch", (schema_cls,), values) |
| 59 |
|
| 60 |
class OptionalDictSchema(ModelToDict): |
| 61 |
_wrapped_model = OptionalSchema |
| 62 |
_wrapped_model_dump_params = {"exclude_unset": True} |
| 63 |
|
| 64 |
return OptionalDictSchema |
| 65 |
|
| 66 |
|
| 67 |
class PatchDictUtil: |
| 68 |
def __getitem__(self, schema_cls: Any) -> Any: |
| 69 |
new_cls = create_patch_schema(schema_cls) |
| 70 |
return Body[new_cls] |
| 71 |
|
| 72 |
|
| 73 |
if TYPE_CHECKING: |
| 74 |
T = TypeVar("T") |
| 75 |
|
| 76 |
class PatchDict(Dict[Any, Any], Generic[T]): |
| 77 |
pass |
| 78 |
|
| 79 |
else: |
| 80 |
PatchDict = PatchDictUtil() |