| 1 |
""" |
| 2 |
Since "Model" word would be very confusing when used in django context, this |
| 3 |
module basically makes an alias for it named "Schema" and adds extra whistles to |
| 4 |
be able to work with django querysets and managers. |
| 5 |
|
| 6 |
The schema is a bit smarter than a standard pydantic Model because it can handle |
| 7 |
dotted attributes and resolver methods. For example:: |
| 8 |
|
| 9 |
|
| 10 |
class UserSchema(User): |
| 11 |
name: str |
| 12 |
initials: str |
| 13 |
boss: str = Field(None, alias="boss.first_name") |
| 14 |
|
| 15 |
@staticmethod |
| 16 |
def resolve_name(obj): |
| 17 |
return f"{obj.first_name} {obj.last_name}" |
| 18 |
|
| 19 |
""" |
| 20 |
|
| 21 |
import warnings |
| 22 |
from typing import ( |
| 23 |
Any, |
| 24 |
Callable, |
| 25 |
Dict, |
| 26 |
Type, |
| 27 |
TypeVar, |
| 28 |
Union, |
| 29 |
no_type_check, |
| 30 |
) |
| 31 |
|
| 32 |
import pydantic |
| 33 |
from django.db.models import Manager, QuerySet |
| 34 |
from django.db.models.fields.files import FieldFile |
| 35 |
from django.template import Variable, VariableDoesNotExist |
| 36 |
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, model_validator |
| 37 |
from pydantic._internal._model_construction import ModelMetaclass |
| 38 |
from pydantic.functional_validators import ModelWrapValidatorHandler |
| 39 |
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue |
| 40 |
from typing_extensions import dataclass_transform |
| 41 |
|
| 42 |
from ninja.signature.utils import get_args_names, has_kwargs |
| 43 |
from ninja.types import DictStrAny |
| 44 |
|
| 45 |
pydantic_version = list(map(int, pydantic.VERSION.split(".")[:2])) |
| 46 |
assert pydantic_version >= [2, 0], "Pydantic 2.0+ required" |
| 47 |
|
| 48 |
__all__ = ["BaseModel", "Field", "DjangoGetter", "Schema"] |
| 49 |
|
| 50 |
S = TypeVar("S", bound="Schema") |
| 51 |
|
| 52 |
|
| 53 |
class DjangoGetter: |
| 54 |
__slots__ = ("_obj", "_schema_cls", "_context", "__dict__") |
| 55 |
|
| 56 |
def __init__(self, obj: Any, schema_cls: Type[S], context: Any = None): |
| 57 |
self._obj = obj |
| 58 |
self._schema_cls = schema_cls |
| 59 |
self._context = context |
| 60 |
|
| 61 |
def __getattr__(self, key: str) -> Any: |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
resolver = self._schema_cls._ninja_resolvers.get(key) |
| 66 |
if resolver: |
| 67 |
value = resolver(getter=self) |
| 68 |
else: |
| 69 |
if isinstance(self._obj, dict): |
| 70 |
if key not in self._obj: |
| 71 |
raise AttributeError(key) |
| 72 |
value = self._obj[key] |
| 73 |
else: |
| 74 |
try: |
| 75 |
value = getattr(self._obj, key) |
| 76 |
except AttributeError: |
| 77 |
try: |
| 78 |
|
| 79 |
value = Variable(key).resolve(self._obj) |
| 80 |
|
| 81 |
|
| 82 |
except VariableDoesNotExist as e: |
| 83 |
raise AttributeError(key) from e |
| 84 |
return self._convert_result(value) |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
def _convert_result(self, result: Any) -> Any: |
| 93 |
if isinstance(result, Manager): |
| 94 |
return list(result.all()) |
| 95 |
|
| 96 |
elif isinstance(result, getattr(QuerySet, "__origin__", QuerySet)): |
| 97 |
return list(result) |
| 98 |
|
| 99 |
if callable(result): |
| 100 |
return result() |
| 101 |
|
| 102 |
elif isinstance(result, FieldFile): |
| 103 |
if not result: |
| 104 |
return None |
| 105 |
return result.url |
| 106 |
|
| 107 |
return result |
| 108 |
|
| 109 |
def __repr__(self) -> str: |
| 110 |
return f"<DjangoGetter: {repr(self._obj)}>" |
| 111 |
|
| 112 |
|
| 113 |
class Resolver: |
| 114 |
__slots__ = ("_func", "_static", "_takes_context") |
| 115 |
_static: bool |
| 116 |
_func: Any |
| 117 |
_takes_context: bool |
| 118 |
|
| 119 |
def __init__(self, func: Union[Callable, staticmethod]): |
| 120 |
if isinstance(func, staticmethod): |
| 121 |
self._static = True |
| 122 |
self._func = func.__func__ |
| 123 |
else: |
| 124 |
self._static = False |
| 125 |
self._func = func |
| 126 |
|
| 127 |
arg_names = get_args_names(self._func) |
| 128 |
self._takes_context = has_kwargs(self._func) or "context" in arg_names |
| 129 |
|
| 130 |
def __call__(self, getter: DjangoGetter) -> Any: |
| 131 |
kwargs = {} |
| 132 |
if self._takes_context: |
| 133 |
kwargs["context"] = getter._context |
| 134 |
|
| 135 |
if self._static: |
| 136 |
return self._func(getter._obj, **kwargs) |
| 137 |
raise NotImplementedError( |
| 138 |
"Non static resolves are not supported yet" |
| 139 |
) |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
@dataclass_transform(kw_only_default=True, field_specifiers=(Field,)) |
| 159 |
class ResolverMetaclass(ModelMetaclass): |
| 160 |
_ninja_resolvers: Dict[str, Resolver] |
| 161 |
|
| 162 |
@no_type_check |
| 163 |
def __new__(cls, name, bases, namespace, **kwargs): |
| 164 |
resolvers = {} |
| 165 |
|
| 166 |
for base in reversed(bases): |
| 167 |
base_resolvers = getattr(base, "_ninja_resolvers", None) |
| 168 |
if base_resolvers: |
| 169 |
resolvers.update(base_resolvers) |
| 170 |
for attr, resolve_func in namespace.items(): |
| 171 |
if not attr.startswith("resolve_"): |
| 172 |
continue |
| 173 |
if ( |
| 174 |
not callable(resolve_func) |
| 175 |
|
| 176 |
and not isinstance(resolve_func, staticmethod) |
| 177 |
): |
| 178 |
continue |
| 179 |
resolvers[attr[8:]] = Resolver(resolve_func) |
| 180 |
|
| 181 |
result = super().__new__(cls, name, bases, namespace, **kwargs) |
| 182 |
result._ninja_resolvers = resolvers |
| 183 |
return result |
| 184 |
|
| 185 |
|
| 186 |
class NinjaGenerateJsonSchema(GenerateJsonSchema): |
| 187 |
def default_schema(self, schema: Any) -> JsonSchemaValue: |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
json_schema = self.generate_inner(schema["schema"]) |
| 192 |
|
| 193 |
default = None |
| 194 |
if "default" in schema and schema["default"] is not None: |
| 195 |
default = self.encode_default(schema["default"]) |
| 196 |
|
| 197 |
if "$ref" in json_schema: |
| 198 |
|
| 199 |
result = {"allOf": [json_schema]} |
| 200 |
else: |
| 201 |
result = json_schema |
| 202 |
|
| 203 |
if default is not None: |
| 204 |
result["default"] = default |
| 205 |
|
| 206 |
return result |
| 207 |
|
| 208 |
|
| 209 |
class Schema(BaseModel, metaclass=ResolverMetaclass): |
| 210 |
model_config = ConfigDict(from_attributes=True) |
| 211 |
|
| 212 |
@model_validator(mode="wrap") |
| 213 |
@classmethod |
| 214 |
def _run_root_validator( |
| 215 |
cls, values: Any, handler: ModelWrapValidatorHandler[S], info: ValidationInfo |
| 216 |
) -> Any: |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
forbids_extra = cls.model_config.get("extra") == "forbid" |
| 222 |
should_validate_assignment = cls.model_config.get("validate_assignment", False) |
| 223 |
if forbids_extra or should_validate_assignment: |
| 224 |
handler(values) |
| 225 |
|
| 226 |
values = DjangoGetter(values, cls, info.context) |
| 227 |
return handler(values) |
| 228 |
|
| 229 |
@classmethod |
| 230 |
def from_orm(cls: Type[S], obj: Any, **kw: Any) -> S: |
| 231 |
return cls.model_validate(obj, **kw) |
| 232 |
|
| 233 |
def dict(self, *a: Any, **kw: Any) -> DictStrAny: |
| 234 |
"Backward compatibility with pydantic 1.x" |
| 235 |
return self.model_dump(*a, **kw) |
| 236 |
|
| 237 |
@classmethod |
| 238 |
def json_schema(cls) -> DictStrAny: |
| 239 |
return cls.model_json_schema(schema_generator=NinjaGenerateJsonSchema) |
| 240 |
|
| 241 |
@classmethod |
| 242 |
def schema(cls) -> DictStrAny: |
| 243 |
warnings.warn( |
| 244 |
".schema() is deprecated, use .json_schema() instead", |
| 245 |
DeprecationWarning, |
| 246 |
stacklevel=2, |
| 247 |
) |
| 248 |
return cls.json_schema() |