fastapi 0.128.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.
- fastapi/__init__.py +25 -0
- fastapi/__main__.py +3 -0
- fastapi/_compat/__init__.py +41 -0
- fastapi/_compat/shared.py +206 -0
- fastapi/_compat/v2.py +568 -0
- fastapi/applications.py +4669 -0
- fastapi/background.py +60 -0
- fastapi/cli.py +13 -0
- fastapi/concurrency.py +41 -0
- fastapi/datastructures.py +183 -0
- fastapi/dependencies/__init__.py +0 -0
- fastapi/dependencies/models.py +193 -0
- fastapi/dependencies/utils.py +1021 -0
- fastapi/encoders.py +346 -0
- fastapi/exception_handlers.py +34 -0
- fastapi/exceptions.py +246 -0
- fastapi/logger.py +3 -0
- fastapi/middleware/__init__.py +1 -0
- fastapi/middleware/asyncexitstack.py +18 -0
- fastapi/middleware/cors.py +1 -0
- fastapi/middleware/gzip.py +1 -0
- fastapi/middleware/httpsredirect.py +3 -0
- fastapi/middleware/trustedhost.py +3 -0
- fastapi/middleware/wsgi.py +1 -0
- fastapi/openapi/__init__.py +0 -0
- fastapi/openapi/constants.py +3 -0
- fastapi/openapi/docs.py +344 -0
- fastapi/openapi/models.py +438 -0
- fastapi/openapi/utils.py +567 -0
- fastapi/param_functions.py +2369 -0
- fastapi/params.py +755 -0
- fastapi/py.typed +0 -0
- fastapi/requests.py +2 -0
- fastapi/responses.py +48 -0
- fastapi/routing.py +4508 -0
- fastapi/security/__init__.py +15 -0
- fastapi/security/api_key.py +318 -0
- fastapi/security/base.py +6 -0
- fastapi/security/http.py +423 -0
- fastapi/security/oauth2.py +663 -0
- fastapi/security/open_id_connect_url.py +94 -0
- fastapi/security/utils.py +10 -0
- fastapi/staticfiles.py +1 -0
- fastapi/templating.py +1 -0
- fastapi/testclient.py +1 -0
- fastapi/types.py +11 -0
- fastapi/utils.py +164 -0
- fastapi/websockets.py +3 -0
- fastapi-0.128.0.dist-info/METADATA +645 -0
- fastapi-0.128.0.dist-info/RECORD +53 -0
- fastapi-0.128.0.dist-info/WHEEL +4 -0
- fastapi-0.128.0.dist-info/entry_points.txt +5 -0
- fastapi-0.128.0.dist-info/licenses/LICENSE +21 -0
fastapi/encoders.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
import datetime
|
|
3
|
+
from collections import defaultdict, deque
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from ipaddress import (
|
|
7
|
+
IPv4Address,
|
|
8
|
+
IPv4Interface,
|
|
9
|
+
IPv4Network,
|
|
10
|
+
IPv6Address,
|
|
11
|
+
IPv6Interface,
|
|
12
|
+
IPv6Network,
|
|
13
|
+
)
|
|
14
|
+
from pathlib import Path, PurePath
|
|
15
|
+
from re import Pattern
|
|
16
|
+
from types import GeneratorType
|
|
17
|
+
from typing import Annotated, Any, Callable, Optional, Union
|
|
18
|
+
from uuid import UUID
|
|
19
|
+
|
|
20
|
+
from annotated_doc import Doc
|
|
21
|
+
from fastapi.exceptions import PydanticV1NotSupportedError
|
|
22
|
+
from fastapi.types import IncEx
|
|
23
|
+
from pydantic import BaseModel
|
|
24
|
+
from pydantic.color import Color
|
|
25
|
+
from pydantic.networks import AnyUrl, NameEmail
|
|
26
|
+
from pydantic.types import SecretBytes, SecretStr
|
|
27
|
+
from pydantic_core import PydanticUndefinedType
|
|
28
|
+
|
|
29
|
+
from ._compat import (
|
|
30
|
+
Url,
|
|
31
|
+
is_pydantic_v1_model_instance,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# Taken from Pydantic v1 as is
|
|
36
|
+
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
|
|
37
|
+
return o.isoformat()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# Adapted from Pydantic v1
|
|
41
|
+
# TODO: pv2 should this return strings instead?
|
|
42
|
+
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
|
|
43
|
+
"""
|
|
44
|
+
Encodes a Decimal as int if there's no exponent, otherwise float
|
|
45
|
+
|
|
46
|
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
|
47
|
+
where an integer (but not int typed) is used. Encoding this as a float
|
|
48
|
+
results in failed round-tripping between encode and parse.
|
|
49
|
+
Our Id type is a prime example of this.
|
|
50
|
+
|
|
51
|
+
>>> decimal_encoder(Decimal("1.0"))
|
|
52
|
+
1.0
|
|
53
|
+
|
|
54
|
+
>>> decimal_encoder(Decimal("1"))
|
|
55
|
+
1
|
|
56
|
+
|
|
57
|
+
>>> decimal_encoder(Decimal("NaN"))
|
|
58
|
+
nan
|
|
59
|
+
"""
|
|
60
|
+
exponent = dec_value.as_tuple().exponent
|
|
61
|
+
if isinstance(exponent, int) and exponent >= 0:
|
|
62
|
+
return int(dec_value)
|
|
63
|
+
else:
|
|
64
|
+
return float(dec_value)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
|
|
68
|
+
bytes: lambda o: o.decode(),
|
|
69
|
+
Color: str,
|
|
70
|
+
datetime.date: isoformat,
|
|
71
|
+
datetime.datetime: isoformat,
|
|
72
|
+
datetime.time: isoformat,
|
|
73
|
+
datetime.timedelta: lambda td: td.total_seconds(),
|
|
74
|
+
Decimal: decimal_encoder,
|
|
75
|
+
Enum: lambda o: o.value,
|
|
76
|
+
frozenset: list,
|
|
77
|
+
deque: list,
|
|
78
|
+
GeneratorType: list,
|
|
79
|
+
IPv4Address: str,
|
|
80
|
+
IPv4Interface: str,
|
|
81
|
+
IPv4Network: str,
|
|
82
|
+
IPv6Address: str,
|
|
83
|
+
IPv6Interface: str,
|
|
84
|
+
IPv6Network: str,
|
|
85
|
+
NameEmail: str,
|
|
86
|
+
Path: str,
|
|
87
|
+
Pattern: lambda o: o.pattern,
|
|
88
|
+
SecretBytes: str,
|
|
89
|
+
SecretStr: str,
|
|
90
|
+
set: list,
|
|
91
|
+
UUID: str,
|
|
92
|
+
Url: str,
|
|
93
|
+
AnyUrl: str,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def generate_encoders_by_class_tuples(
|
|
98
|
+
type_encoder_map: dict[Any, Callable[[Any], Any]],
|
|
99
|
+
) -> dict[Callable[[Any], Any], tuple[Any, ...]]:
|
|
100
|
+
encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict(
|
|
101
|
+
tuple
|
|
102
|
+
)
|
|
103
|
+
for type_, encoder in type_encoder_map.items():
|
|
104
|
+
encoders_by_class_tuples[encoder] += (type_,)
|
|
105
|
+
return encoders_by_class_tuples
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def jsonable_encoder(
|
|
112
|
+
obj: Annotated[
|
|
113
|
+
Any,
|
|
114
|
+
Doc(
|
|
115
|
+
"""
|
|
116
|
+
The input object to convert to JSON.
|
|
117
|
+
"""
|
|
118
|
+
),
|
|
119
|
+
],
|
|
120
|
+
include: Annotated[
|
|
121
|
+
Optional[IncEx],
|
|
122
|
+
Doc(
|
|
123
|
+
"""
|
|
124
|
+
Pydantic's `include` parameter, passed to Pydantic models to set the
|
|
125
|
+
fields to include.
|
|
126
|
+
"""
|
|
127
|
+
),
|
|
128
|
+
] = None,
|
|
129
|
+
exclude: Annotated[
|
|
130
|
+
Optional[IncEx],
|
|
131
|
+
Doc(
|
|
132
|
+
"""
|
|
133
|
+
Pydantic's `exclude` parameter, passed to Pydantic models to set the
|
|
134
|
+
fields to exclude.
|
|
135
|
+
"""
|
|
136
|
+
),
|
|
137
|
+
] = None,
|
|
138
|
+
by_alias: Annotated[
|
|
139
|
+
bool,
|
|
140
|
+
Doc(
|
|
141
|
+
"""
|
|
142
|
+
Pydantic's `by_alias` parameter, passed to Pydantic models to define if
|
|
143
|
+
the output should use the alias names (when provided) or the Python
|
|
144
|
+
attribute names. In an API, if you set an alias, it's probably because you
|
|
145
|
+
want to use it in the result, so you probably want to leave this set to
|
|
146
|
+
`True`.
|
|
147
|
+
"""
|
|
148
|
+
),
|
|
149
|
+
] = True,
|
|
150
|
+
exclude_unset: Annotated[
|
|
151
|
+
bool,
|
|
152
|
+
Doc(
|
|
153
|
+
"""
|
|
154
|
+
Pydantic's `exclude_unset` parameter, passed to Pydantic models to define
|
|
155
|
+
if it should exclude from the output the fields that were not explicitly
|
|
156
|
+
set (and that only had their default values).
|
|
157
|
+
"""
|
|
158
|
+
),
|
|
159
|
+
] = False,
|
|
160
|
+
exclude_defaults: Annotated[
|
|
161
|
+
bool,
|
|
162
|
+
Doc(
|
|
163
|
+
"""
|
|
164
|
+
Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define
|
|
165
|
+
if it should exclude from the output the fields that had the same default
|
|
166
|
+
value, even when they were explicitly set.
|
|
167
|
+
"""
|
|
168
|
+
),
|
|
169
|
+
] = False,
|
|
170
|
+
exclude_none: Annotated[
|
|
171
|
+
bool,
|
|
172
|
+
Doc(
|
|
173
|
+
"""
|
|
174
|
+
Pydantic's `exclude_none` parameter, passed to Pydantic models to define
|
|
175
|
+
if it should exclude from the output any fields that have a `None` value.
|
|
176
|
+
"""
|
|
177
|
+
),
|
|
178
|
+
] = False,
|
|
179
|
+
custom_encoder: Annotated[
|
|
180
|
+
Optional[dict[Any, Callable[[Any], Any]]],
|
|
181
|
+
Doc(
|
|
182
|
+
"""
|
|
183
|
+
Pydantic's `custom_encoder` parameter, passed to Pydantic models to define
|
|
184
|
+
a custom encoder.
|
|
185
|
+
"""
|
|
186
|
+
),
|
|
187
|
+
] = None,
|
|
188
|
+
sqlalchemy_safe: Annotated[
|
|
189
|
+
bool,
|
|
190
|
+
Doc(
|
|
191
|
+
"""
|
|
192
|
+
Exclude from the output any fields that start with the name `_sa`.
|
|
193
|
+
|
|
194
|
+
This is mainly a hack for compatibility with SQLAlchemy objects, they
|
|
195
|
+
store internal SQLAlchemy-specific state in attributes named with `_sa`,
|
|
196
|
+
and those objects can't (and shouldn't be) serialized to JSON.
|
|
197
|
+
"""
|
|
198
|
+
),
|
|
199
|
+
] = True,
|
|
200
|
+
) -> Any:
|
|
201
|
+
"""
|
|
202
|
+
Convert any object to something that can be encoded in JSON.
|
|
203
|
+
|
|
204
|
+
This is used internally by FastAPI to make sure anything you return can be
|
|
205
|
+
encoded as JSON before it is sent to the client.
|
|
206
|
+
|
|
207
|
+
You can also use it yourself, for example to convert objects before saving them
|
|
208
|
+
in a database that supports only JSON.
|
|
209
|
+
|
|
210
|
+
Read more about it in the
|
|
211
|
+
[FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
|
|
212
|
+
"""
|
|
213
|
+
custom_encoder = custom_encoder or {}
|
|
214
|
+
if custom_encoder:
|
|
215
|
+
if type(obj) in custom_encoder:
|
|
216
|
+
return custom_encoder[type(obj)](obj)
|
|
217
|
+
else:
|
|
218
|
+
for encoder_type, encoder_instance in custom_encoder.items():
|
|
219
|
+
if isinstance(obj, encoder_type):
|
|
220
|
+
return encoder_instance(obj)
|
|
221
|
+
if include is not None and not isinstance(include, (set, dict)):
|
|
222
|
+
include = set(include)
|
|
223
|
+
if exclude is not None and not isinstance(exclude, (set, dict)):
|
|
224
|
+
exclude = set(exclude)
|
|
225
|
+
if isinstance(obj, BaseModel):
|
|
226
|
+
obj_dict = obj.model_dump(
|
|
227
|
+
mode="json",
|
|
228
|
+
include=include,
|
|
229
|
+
exclude=exclude,
|
|
230
|
+
by_alias=by_alias,
|
|
231
|
+
exclude_unset=exclude_unset,
|
|
232
|
+
exclude_none=exclude_none,
|
|
233
|
+
exclude_defaults=exclude_defaults,
|
|
234
|
+
)
|
|
235
|
+
return jsonable_encoder(
|
|
236
|
+
obj_dict,
|
|
237
|
+
exclude_none=exclude_none,
|
|
238
|
+
exclude_defaults=exclude_defaults,
|
|
239
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
240
|
+
)
|
|
241
|
+
if dataclasses.is_dataclass(obj):
|
|
242
|
+
assert not isinstance(obj, type)
|
|
243
|
+
obj_dict = dataclasses.asdict(obj)
|
|
244
|
+
return jsonable_encoder(
|
|
245
|
+
obj_dict,
|
|
246
|
+
include=include,
|
|
247
|
+
exclude=exclude,
|
|
248
|
+
by_alias=by_alias,
|
|
249
|
+
exclude_unset=exclude_unset,
|
|
250
|
+
exclude_defaults=exclude_defaults,
|
|
251
|
+
exclude_none=exclude_none,
|
|
252
|
+
custom_encoder=custom_encoder,
|
|
253
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
254
|
+
)
|
|
255
|
+
if isinstance(obj, Enum):
|
|
256
|
+
return obj.value
|
|
257
|
+
if isinstance(obj, PurePath):
|
|
258
|
+
return str(obj)
|
|
259
|
+
if isinstance(obj, (str, int, float, type(None))):
|
|
260
|
+
return obj
|
|
261
|
+
if isinstance(obj, PydanticUndefinedType):
|
|
262
|
+
return None
|
|
263
|
+
if isinstance(obj, dict):
|
|
264
|
+
encoded_dict = {}
|
|
265
|
+
allowed_keys = set(obj.keys())
|
|
266
|
+
if include is not None:
|
|
267
|
+
allowed_keys &= set(include)
|
|
268
|
+
if exclude is not None:
|
|
269
|
+
allowed_keys -= set(exclude)
|
|
270
|
+
for key, value in obj.items():
|
|
271
|
+
if (
|
|
272
|
+
(
|
|
273
|
+
not sqlalchemy_safe
|
|
274
|
+
or (not isinstance(key, str))
|
|
275
|
+
or (not key.startswith("_sa"))
|
|
276
|
+
)
|
|
277
|
+
and (value is not None or not exclude_none)
|
|
278
|
+
and key in allowed_keys
|
|
279
|
+
):
|
|
280
|
+
encoded_key = jsonable_encoder(
|
|
281
|
+
key,
|
|
282
|
+
by_alias=by_alias,
|
|
283
|
+
exclude_unset=exclude_unset,
|
|
284
|
+
exclude_none=exclude_none,
|
|
285
|
+
custom_encoder=custom_encoder,
|
|
286
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
287
|
+
)
|
|
288
|
+
encoded_value = jsonable_encoder(
|
|
289
|
+
value,
|
|
290
|
+
by_alias=by_alias,
|
|
291
|
+
exclude_unset=exclude_unset,
|
|
292
|
+
exclude_none=exclude_none,
|
|
293
|
+
custom_encoder=custom_encoder,
|
|
294
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
295
|
+
)
|
|
296
|
+
encoded_dict[encoded_key] = encoded_value
|
|
297
|
+
return encoded_dict
|
|
298
|
+
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
|
|
299
|
+
encoded_list = []
|
|
300
|
+
for item in obj:
|
|
301
|
+
encoded_list.append(
|
|
302
|
+
jsonable_encoder(
|
|
303
|
+
item,
|
|
304
|
+
include=include,
|
|
305
|
+
exclude=exclude,
|
|
306
|
+
by_alias=by_alias,
|
|
307
|
+
exclude_unset=exclude_unset,
|
|
308
|
+
exclude_defaults=exclude_defaults,
|
|
309
|
+
exclude_none=exclude_none,
|
|
310
|
+
custom_encoder=custom_encoder,
|
|
311
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
return encoded_list
|
|
315
|
+
|
|
316
|
+
if type(obj) in ENCODERS_BY_TYPE:
|
|
317
|
+
return ENCODERS_BY_TYPE[type(obj)](obj)
|
|
318
|
+
for encoder, classes_tuple in encoders_by_class_tuples.items():
|
|
319
|
+
if isinstance(obj, classes_tuple):
|
|
320
|
+
return encoder(obj)
|
|
321
|
+
if is_pydantic_v1_model_instance(obj):
|
|
322
|
+
raise PydanticV1NotSupportedError(
|
|
323
|
+
"pydantic.v1 models are no longer supported by FastAPI."
|
|
324
|
+
f" Please update the model {obj!r}."
|
|
325
|
+
)
|
|
326
|
+
try:
|
|
327
|
+
data = dict(obj)
|
|
328
|
+
except Exception as e:
|
|
329
|
+
errors: list[Exception] = []
|
|
330
|
+
errors.append(e)
|
|
331
|
+
try:
|
|
332
|
+
data = vars(obj)
|
|
333
|
+
except Exception as e:
|
|
334
|
+
errors.append(e)
|
|
335
|
+
raise ValueError(errors) from e
|
|
336
|
+
return jsonable_encoder(
|
|
337
|
+
data,
|
|
338
|
+
include=include,
|
|
339
|
+
exclude=exclude,
|
|
340
|
+
by_alias=by_alias,
|
|
341
|
+
exclude_unset=exclude_unset,
|
|
342
|
+
exclude_defaults=exclude_defaults,
|
|
343
|
+
exclude_none=exclude_none,
|
|
344
|
+
custom_encoder=custom_encoder,
|
|
345
|
+
sqlalchemy_safe=sqlalchemy_safe,
|
|
346
|
+
)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from fastapi.encoders import jsonable_encoder
|
|
2
|
+
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
|
|
3
|
+
from fastapi.utils import is_body_allowed_for_status_code
|
|
4
|
+
from fastapi.websockets import WebSocket
|
|
5
|
+
from starlette.exceptions import HTTPException
|
|
6
|
+
from starlette.requests import Request
|
|
7
|
+
from starlette.responses import JSONResponse, Response
|
|
8
|
+
from starlette.status import WS_1008_POLICY_VIOLATION
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
|
|
12
|
+
headers = getattr(exc, "headers", None)
|
|
13
|
+
if not is_body_allowed_for_status_code(exc.status_code):
|
|
14
|
+
return Response(status_code=exc.status_code, headers=headers)
|
|
15
|
+
return JSONResponse(
|
|
16
|
+
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def request_validation_exception_handler(
|
|
21
|
+
request: Request, exc: RequestValidationError
|
|
22
|
+
) -> JSONResponse:
|
|
23
|
+
return JSONResponse(
|
|
24
|
+
status_code=422,
|
|
25
|
+
content={"detail": jsonable_encoder(exc.errors())},
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def websocket_request_validation_exception_handler(
|
|
30
|
+
websocket: WebSocket, exc: WebSocketRequestValidationError
|
|
31
|
+
) -> None:
|
|
32
|
+
await websocket.close(
|
|
33
|
+
code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())
|
|
34
|
+
)
|
fastapi/exceptions.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Annotated, Any, Optional, TypedDict, Union
|
|
3
|
+
|
|
4
|
+
from annotated_doc import Doc
|
|
5
|
+
from pydantic import BaseModel, create_model
|
|
6
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
7
|
+
from starlette.exceptions import WebSocketException as StarletteWebSocketException
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EndpointContext(TypedDict, total=False):
|
|
11
|
+
function: str
|
|
12
|
+
path: str
|
|
13
|
+
file: str
|
|
14
|
+
line: int
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HTTPException(StarletteHTTPException):
|
|
18
|
+
"""
|
|
19
|
+
An HTTP exception you can raise in your own code to show errors to the client.
|
|
20
|
+
|
|
21
|
+
This is for client errors, invalid authentication, invalid data, etc. Not for server
|
|
22
|
+
errors in your code.
|
|
23
|
+
|
|
24
|
+
Read more about it in the
|
|
25
|
+
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
|
|
26
|
+
|
|
27
|
+
## Example
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from fastapi import FastAPI, HTTPException
|
|
31
|
+
|
|
32
|
+
app = FastAPI()
|
|
33
|
+
|
|
34
|
+
items = {"foo": "The Foo Wrestlers"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.get("/items/{item_id}")
|
|
38
|
+
async def read_item(item_id: str):
|
|
39
|
+
if item_id not in items:
|
|
40
|
+
raise HTTPException(status_code=404, detail="Item not found")
|
|
41
|
+
return {"item": items[item_id]}
|
|
42
|
+
```
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
status_code: Annotated[
|
|
48
|
+
int,
|
|
49
|
+
Doc(
|
|
50
|
+
"""
|
|
51
|
+
HTTP status code to send to the client.
|
|
52
|
+
"""
|
|
53
|
+
),
|
|
54
|
+
],
|
|
55
|
+
detail: Annotated[
|
|
56
|
+
Any,
|
|
57
|
+
Doc(
|
|
58
|
+
"""
|
|
59
|
+
Any data to be sent to the client in the `detail` key of the JSON
|
|
60
|
+
response.
|
|
61
|
+
"""
|
|
62
|
+
),
|
|
63
|
+
] = None,
|
|
64
|
+
headers: Annotated[
|
|
65
|
+
Optional[dict[str, str]],
|
|
66
|
+
Doc(
|
|
67
|
+
"""
|
|
68
|
+
Any headers to send to the client in the response.
|
|
69
|
+
"""
|
|
70
|
+
),
|
|
71
|
+
] = None,
|
|
72
|
+
) -> None:
|
|
73
|
+
super().__init__(status_code=status_code, detail=detail, headers=headers)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class WebSocketException(StarletteWebSocketException):
|
|
77
|
+
"""
|
|
78
|
+
A WebSocket exception you can raise in your own code to show errors to the client.
|
|
79
|
+
|
|
80
|
+
This is for client errors, invalid authentication, invalid data, etc. Not for server
|
|
81
|
+
errors in your code.
|
|
82
|
+
|
|
83
|
+
Read more about it in the
|
|
84
|
+
[FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
|
85
|
+
|
|
86
|
+
## Example
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from typing import Annotated
|
|
90
|
+
|
|
91
|
+
from fastapi import (
|
|
92
|
+
Cookie,
|
|
93
|
+
FastAPI,
|
|
94
|
+
WebSocket,
|
|
95
|
+
WebSocketException,
|
|
96
|
+
status,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
app = FastAPI()
|
|
100
|
+
|
|
101
|
+
@app.websocket("/items/{item_id}/ws")
|
|
102
|
+
async def websocket_endpoint(
|
|
103
|
+
*,
|
|
104
|
+
websocket: WebSocket,
|
|
105
|
+
session: Annotated[str | None, Cookie()] = None,
|
|
106
|
+
item_id: str,
|
|
107
|
+
):
|
|
108
|
+
if session is None:
|
|
109
|
+
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
|
|
110
|
+
await websocket.accept()
|
|
111
|
+
while True:
|
|
112
|
+
data = await websocket.receive_text()
|
|
113
|
+
await websocket.send_text(f"Session cookie is: {session}")
|
|
114
|
+
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
|
|
115
|
+
```
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
code: Annotated[
|
|
121
|
+
int,
|
|
122
|
+
Doc(
|
|
123
|
+
"""
|
|
124
|
+
A closing code from the
|
|
125
|
+
[valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
|
|
126
|
+
"""
|
|
127
|
+
),
|
|
128
|
+
],
|
|
129
|
+
reason: Annotated[
|
|
130
|
+
Union[str, None],
|
|
131
|
+
Doc(
|
|
132
|
+
"""
|
|
133
|
+
The reason to close the WebSocket connection.
|
|
134
|
+
|
|
135
|
+
It is UTF-8-encoded data. The interpretation of the reason is up to the
|
|
136
|
+
application, it is not specified by the WebSocket specification.
|
|
137
|
+
|
|
138
|
+
It could contain text that could be human-readable or interpretable
|
|
139
|
+
by the client code, etc.
|
|
140
|
+
"""
|
|
141
|
+
),
|
|
142
|
+
] = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
super().__init__(code=code, reason=reason)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
RequestErrorModel: type[BaseModel] = create_model("Request")
|
|
148
|
+
WebSocketErrorModel: type[BaseModel] = create_model("WebSocket")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class FastAPIError(RuntimeError):
|
|
152
|
+
"""
|
|
153
|
+
A generic, FastAPI-specific error.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class DependencyScopeError(FastAPIError):
|
|
158
|
+
"""
|
|
159
|
+
A dependency declared that it depends on another dependency with an invalid
|
|
160
|
+
(narrower) scope.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class ValidationException(Exception):
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
errors: Sequence[Any],
|
|
168
|
+
*,
|
|
169
|
+
endpoint_ctx: Optional[EndpointContext] = None,
|
|
170
|
+
) -> None:
|
|
171
|
+
self._errors = errors
|
|
172
|
+
self.endpoint_ctx = endpoint_ctx
|
|
173
|
+
|
|
174
|
+
ctx = endpoint_ctx or {}
|
|
175
|
+
self.endpoint_function = ctx.get("function")
|
|
176
|
+
self.endpoint_path = ctx.get("path")
|
|
177
|
+
self.endpoint_file = ctx.get("file")
|
|
178
|
+
self.endpoint_line = ctx.get("line")
|
|
179
|
+
|
|
180
|
+
def errors(self) -> Sequence[Any]:
|
|
181
|
+
return self._errors
|
|
182
|
+
|
|
183
|
+
def _format_endpoint_context(self) -> str:
|
|
184
|
+
if not (self.endpoint_file and self.endpoint_line and self.endpoint_function):
|
|
185
|
+
if self.endpoint_path:
|
|
186
|
+
return f"\n Endpoint: {self.endpoint_path}"
|
|
187
|
+
return ""
|
|
188
|
+
|
|
189
|
+
context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}'
|
|
190
|
+
if self.endpoint_path:
|
|
191
|
+
context += f"\n {self.endpoint_path}"
|
|
192
|
+
return context
|
|
193
|
+
|
|
194
|
+
def __str__(self) -> str:
|
|
195
|
+
message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n"
|
|
196
|
+
for err in self._errors:
|
|
197
|
+
message += f" {err}\n"
|
|
198
|
+
message += self._format_endpoint_context()
|
|
199
|
+
return message.rstrip()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class RequestValidationError(ValidationException):
|
|
203
|
+
def __init__(
|
|
204
|
+
self,
|
|
205
|
+
errors: Sequence[Any],
|
|
206
|
+
*,
|
|
207
|
+
body: Any = None,
|
|
208
|
+
endpoint_ctx: Optional[EndpointContext] = None,
|
|
209
|
+
) -> None:
|
|
210
|
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
|
211
|
+
self.body = body
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class WebSocketRequestValidationError(ValidationException):
|
|
215
|
+
def __init__(
|
|
216
|
+
self,
|
|
217
|
+
errors: Sequence[Any],
|
|
218
|
+
*,
|
|
219
|
+
endpoint_ctx: Optional[EndpointContext] = None,
|
|
220
|
+
) -> None:
|
|
221
|
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class ResponseValidationError(ValidationException):
|
|
225
|
+
def __init__(
|
|
226
|
+
self,
|
|
227
|
+
errors: Sequence[Any],
|
|
228
|
+
*,
|
|
229
|
+
body: Any = None,
|
|
230
|
+
endpoint_ctx: Optional[EndpointContext] = None,
|
|
231
|
+
) -> None:
|
|
232
|
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
|
233
|
+
self.body = body
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class PydanticV1NotSupportedError(FastAPIError):
|
|
237
|
+
"""
|
|
238
|
+
A pydantic.v1 model is used, which is no longer supported.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class FastAPIDeprecationWarning(UserWarning):
|
|
243
|
+
"""
|
|
244
|
+
A custom deprecation warning as DeprecationWarning is ignored
|
|
245
|
+
Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
|
|
246
|
+
"""
|
fastapi/logger.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from starlette.middleware import Middleware as Middleware
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from contextlib import AsyncExitStack
|
|
2
|
+
|
|
3
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# Used mainly to close files after the request is done, dependencies are closed
|
|
7
|
+
# in their own AsyncExitStack
|
|
8
|
+
class AsyncExitStackMiddleware:
|
|
9
|
+
def __init__(
|
|
10
|
+
self, app: ASGIApp, context_name: str = "fastapi_middleware_astack"
|
|
11
|
+
) -> None:
|
|
12
|
+
self.app = app
|
|
13
|
+
self.context_name = context_name
|
|
14
|
+
|
|
15
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
16
|
+
async with AsyncExitStack() as stack:
|
|
17
|
+
scope[self.context_name] = stack
|
|
18
|
+
await self.app(scope, receive, send)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa
|
|
File without changes
|