fastapi 0.118.3__py3-none-any.whl → 0.119.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fastapi might be problematic. Click here for more details.

fastapi/_compat/v1.py ADDED
@@ -0,0 +1,334 @@
1
+ from copy import copy
2
+ from dataclasses import dataclass, is_dataclass
3
+ from enum import Enum
4
+ from typing import (
5
+ Any,
6
+ Callable,
7
+ Dict,
8
+ List,
9
+ Sequence,
10
+ Set,
11
+ Tuple,
12
+ Type,
13
+ Union,
14
+ )
15
+
16
+ from fastapi._compat import shared
17
+ from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX
18
+ from fastapi.types import ModelNameMap
19
+ from pydantic.version import VERSION as PYDANTIC_VERSION
20
+ from typing_extensions import Literal
21
+
22
+ PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2])
23
+ PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2
24
+ # Keeping old "Required" functionality from Pydantic V1, without
25
+ # shadowing typing.Required.
26
+ RequiredParam: Any = Ellipsis
27
+
28
+ if not PYDANTIC_V2:
29
+ from pydantic import BaseConfig as BaseConfig
30
+ from pydantic import BaseModel as BaseModel
31
+ from pydantic import ValidationError as ValidationError
32
+ from pydantic import create_model as create_model
33
+ from pydantic.class_validators import Validator as Validator
34
+ from pydantic.color import Color as Color
35
+ from pydantic.error_wrappers import ErrorWrapper as ErrorWrapper
36
+ from pydantic.errors import MissingError
37
+ from pydantic.fields import ( # type: ignore[attr-defined]
38
+ SHAPE_FROZENSET,
39
+ SHAPE_LIST,
40
+ SHAPE_SEQUENCE,
41
+ SHAPE_SET,
42
+ SHAPE_SINGLETON,
43
+ SHAPE_TUPLE,
44
+ SHAPE_TUPLE_ELLIPSIS,
45
+ )
46
+ from pydantic.fields import FieldInfo as FieldInfo
47
+ from pydantic.fields import ModelField as ModelField # type: ignore[attr-defined]
48
+ from pydantic.fields import Undefined as Undefined # type: ignore[attr-defined]
49
+ from pydantic.fields import ( # type: ignore[attr-defined]
50
+ UndefinedType as UndefinedType,
51
+ )
52
+ from pydantic.networks import AnyUrl as AnyUrl
53
+ from pydantic.networks import NameEmail as NameEmail
54
+ from pydantic.schema import TypeModelSet as TypeModelSet
55
+ from pydantic.schema import (
56
+ field_schema,
57
+ get_flat_models_from_fields,
58
+ model_process_schema,
59
+ )
60
+ from pydantic.schema import (
61
+ get_annotation_from_field_info as get_annotation_from_field_info,
62
+ )
63
+ from pydantic.schema import get_flat_models_from_field as get_flat_models_from_field
64
+ from pydantic.schema import get_model_name_map as get_model_name_map
65
+ from pydantic.types import SecretBytes as SecretBytes
66
+ from pydantic.types import SecretStr as SecretStr
67
+ from pydantic.typing import evaluate_forwardref as evaluate_forwardref
68
+ from pydantic.utils import lenient_issubclass as lenient_issubclass
69
+
70
+
71
+ else:
72
+ from pydantic.v1 import BaseConfig as BaseConfig # type: ignore[assignment]
73
+ from pydantic.v1 import BaseModel as BaseModel # type: ignore[assignment]
74
+ from pydantic.v1 import ( # type: ignore[assignment]
75
+ ValidationError as ValidationError,
76
+ )
77
+ from pydantic.v1 import create_model as create_model # type: ignore[no-redef]
78
+ from pydantic.v1.class_validators import Validator as Validator
79
+ from pydantic.v1.color import Color as Color # type: ignore[assignment]
80
+ from pydantic.v1.error_wrappers import ErrorWrapper as ErrorWrapper
81
+ from pydantic.v1.errors import MissingError
82
+ from pydantic.v1.fields import (
83
+ SHAPE_FROZENSET,
84
+ SHAPE_LIST,
85
+ SHAPE_SEQUENCE,
86
+ SHAPE_SET,
87
+ SHAPE_SINGLETON,
88
+ SHAPE_TUPLE,
89
+ SHAPE_TUPLE_ELLIPSIS,
90
+ )
91
+ from pydantic.v1.fields import FieldInfo as FieldInfo # type: ignore[assignment]
92
+ from pydantic.v1.fields import ModelField as ModelField
93
+ from pydantic.v1.fields import Undefined as Undefined
94
+ from pydantic.v1.fields import UndefinedType as UndefinedType
95
+ from pydantic.v1.networks import AnyUrl as AnyUrl
96
+ from pydantic.v1.networks import ( # type: ignore[assignment]
97
+ NameEmail as NameEmail,
98
+ )
99
+ from pydantic.v1.schema import TypeModelSet as TypeModelSet
100
+ from pydantic.v1.schema import (
101
+ field_schema,
102
+ get_flat_models_from_fields,
103
+ model_process_schema,
104
+ )
105
+ from pydantic.v1.schema import (
106
+ get_annotation_from_field_info as get_annotation_from_field_info,
107
+ )
108
+ from pydantic.v1.schema import (
109
+ get_flat_models_from_field as get_flat_models_from_field,
110
+ )
111
+ from pydantic.v1.schema import get_model_name_map as get_model_name_map
112
+ from pydantic.v1.types import ( # type: ignore[assignment]
113
+ SecretBytes as SecretBytes,
114
+ )
115
+ from pydantic.v1.types import ( # type: ignore[assignment]
116
+ SecretStr as SecretStr,
117
+ )
118
+ from pydantic.v1.typing import evaluate_forwardref as evaluate_forwardref
119
+ from pydantic.v1.utils import lenient_issubclass as lenient_issubclass
120
+
121
+
122
+ GetJsonSchemaHandler = Any
123
+ JsonSchemaValue = Dict[str, Any]
124
+ CoreSchema = Any
125
+ Url = AnyUrl
126
+
127
+ sequence_shapes = {
128
+ SHAPE_LIST,
129
+ SHAPE_SET,
130
+ SHAPE_FROZENSET,
131
+ SHAPE_TUPLE,
132
+ SHAPE_SEQUENCE,
133
+ SHAPE_TUPLE_ELLIPSIS,
134
+ }
135
+ sequence_shape_to_type = {
136
+ SHAPE_LIST: list,
137
+ SHAPE_SET: set,
138
+ SHAPE_TUPLE: tuple,
139
+ SHAPE_SEQUENCE: list,
140
+ SHAPE_TUPLE_ELLIPSIS: list,
141
+ }
142
+
143
+
144
+ @dataclass
145
+ class GenerateJsonSchema:
146
+ ref_template: str
147
+
148
+
149
+ class PydanticSchemaGenerationError(Exception):
150
+ pass
151
+
152
+
153
+ RequestErrorModel: Type[BaseModel] = create_model("Request")
154
+
155
+
156
+ def with_info_plain_validator_function(
157
+ function: Callable[..., Any],
158
+ *,
159
+ ref: Union[str, None] = None,
160
+ metadata: Any = None,
161
+ serialization: Any = None,
162
+ ) -> Any:
163
+ return {}
164
+
165
+
166
+ def get_model_definitions(
167
+ *,
168
+ flat_models: Set[Union[Type[BaseModel], Type[Enum]]],
169
+ model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
170
+ ) -> Dict[str, Any]:
171
+ definitions: Dict[str, Dict[str, Any]] = {}
172
+ for model in flat_models:
173
+ m_schema, m_definitions, m_nested_models = model_process_schema(
174
+ model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
175
+ )
176
+ definitions.update(m_definitions)
177
+ model_name = model_name_map[model]
178
+ definitions[model_name] = m_schema
179
+ for m_schema in definitions.values():
180
+ if "description" in m_schema:
181
+ m_schema["description"] = m_schema["description"].split("\f")[0]
182
+ return definitions
183
+
184
+
185
+ def is_pv1_scalar_field(field: ModelField) -> bool:
186
+ from fastapi import params
187
+
188
+ field_info = field.field_info
189
+ if not (
190
+ field.shape == SHAPE_SINGLETON
191
+ and not lenient_issubclass(field.type_, BaseModel)
192
+ and not lenient_issubclass(field.type_, dict)
193
+ and not shared.field_annotation_is_sequence(field.type_)
194
+ and not is_dataclass(field.type_)
195
+ and not isinstance(field_info, params.Body)
196
+ ):
197
+ return False
198
+ if field.sub_fields:
199
+ if not all(is_pv1_scalar_field(f) for f in field.sub_fields):
200
+ return False
201
+ return True
202
+
203
+
204
+ def is_pv1_scalar_sequence_field(field: ModelField) -> bool:
205
+ if (field.shape in sequence_shapes) and not lenient_issubclass(
206
+ field.type_, BaseModel
207
+ ):
208
+ if field.sub_fields is not None:
209
+ for sub_field in field.sub_fields:
210
+ if not is_pv1_scalar_field(sub_field):
211
+ return False
212
+ return True
213
+ if shared._annotation_is_sequence(field.type_):
214
+ return True
215
+ return False
216
+
217
+
218
+ def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
219
+ use_errors: List[Any] = []
220
+ for error in errors:
221
+ if isinstance(error, ErrorWrapper):
222
+ new_errors = ValidationError( # type: ignore[call-arg]
223
+ errors=[error], model=RequestErrorModel
224
+ ).errors()
225
+ use_errors.extend(new_errors)
226
+ elif isinstance(error, list):
227
+ use_errors.extend(_normalize_errors(error))
228
+ else:
229
+ use_errors.append(error)
230
+ return use_errors
231
+
232
+
233
+ def _regenerate_error_with_loc(
234
+ *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
235
+ ) -> List[Dict[str, Any]]:
236
+ updated_loc_errors: List[Any] = [
237
+ {**err, "loc": loc_prefix + err.get("loc", ())}
238
+ for err in _normalize_errors(errors)
239
+ ]
240
+
241
+ return updated_loc_errors
242
+
243
+
244
+ def _model_rebuild(model: Type[BaseModel]) -> None:
245
+ model.update_forward_refs()
246
+
247
+
248
+ def _model_dump(
249
+ model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
250
+ ) -> Any:
251
+ return model.dict(**kwargs)
252
+
253
+
254
+ def _get_model_config(model: BaseModel) -> Any:
255
+ return model.__config__ # type: ignore[attr-defined]
256
+
257
+
258
+ def get_schema_from_model_field(
259
+ *,
260
+ field: ModelField,
261
+ model_name_map: ModelNameMap,
262
+ field_mapping: Dict[
263
+ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
264
+ ],
265
+ separate_input_output_schemas: bool = True,
266
+ ) -> Dict[str, Any]:
267
+ return field_schema( # type: ignore[no-any-return]
268
+ field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
269
+ )[0]
270
+
271
+
272
+ # def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:
273
+ # models = get_flat_models_from_fields(fields, known_models=set())
274
+ # return get_model_name_map(models) # type: ignore[no-any-return]
275
+
276
+
277
+ def get_definitions(
278
+ *,
279
+ fields: List[ModelField],
280
+ model_name_map: ModelNameMap,
281
+ separate_input_output_schemas: bool = True,
282
+ ) -> Tuple[
283
+ Dict[Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
284
+ Dict[str, Dict[str, Any]],
285
+ ]:
286
+ models = get_flat_models_from_fields(fields, known_models=set())
287
+ return {}, get_model_definitions(flat_models=models, model_name_map=model_name_map)
288
+
289
+
290
+ def is_scalar_field(field: ModelField) -> bool:
291
+ return is_pv1_scalar_field(field)
292
+
293
+
294
+ def is_sequence_field(field: ModelField) -> bool:
295
+ return field.shape in sequence_shapes or shared._annotation_is_sequence(field.type_)
296
+
297
+
298
+ def is_scalar_sequence_field(field: ModelField) -> bool:
299
+ return is_pv1_scalar_sequence_field(field)
300
+
301
+
302
+ def is_bytes_field(field: ModelField) -> bool:
303
+ return lenient_issubclass(field.type_, bytes) # type: ignore[no-any-return]
304
+
305
+
306
+ def is_bytes_sequence_field(field: ModelField) -> bool:
307
+ return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes)
308
+
309
+
310
+ def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
311
+ return copy(field_info)
312
+
313
+
314
+ def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
315
+ return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return]
316
+
317
+
318
+ def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
319
+ missing_field_error = ErrorWrapper(MissingError(), loc=loc)
320
+ new_error = ValidationError([missing_field_error], RequestErrorModel)
321
+ return new_error.errors()[0] # type: ignore[return-value]
322
+
323
+
324
+ def create_body_model(
325
+ *, fields: Sequence[ModelField], model_name: str
326
+ ) -> Type[BaseModel]:
327
+ BodyModel = create_model(model_name)
328
+ for f in fields:
329
+ BodyModel.__fields__[f.name] = f # type: ignore[index]
330
+ return BodyModel
331
+
332
+
333
+ def get_model_fields(model: Type[BaseModel]) -> List[ModelField]:
334
+ return list(model.__fields__.values()) # type: ignore[attr-defined]