Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.11/site-packages/_yaml/__init__.py +33 -0
- lib/python3.11/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/einops-0.8.2.dist-info/INSTALLER +1 -0
- lib/python3.11/site-packages/einops-0.8.2.dist-info/METADATA +394 -0
- lib/python3.11/site-packages/einops-0.8.2.dist-info/RECORD +58 -0
- lib/python3.11/site-packages/einops-0.8.2.dist-info/WHEEL +4 -0
- lib/python3.11/site-packages/einops-0.8.2.dist-info/licenses/LICENSE +21 -0
- lib/python3.11/site-packages/einops/__pycache__/packing.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/einops/__pycache__/parsing.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/SKILL.md +436 -0
- lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md +142 -0
- lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md +76 -0
- lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md +105 -0
- lib/python3.11/site-packages/fastapi/__init__.py +25 -0
- lib/python3.11/site-packages/fastapi/__main__.py +3 -0
- lib/python3.11/site-packages/fastapi/_compat/__init__.py +40 -0
- lib/python3.11/site-packages/fastapi/_compat/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/_compat/__pycache__/shared.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/_compat/__pycache__/v2.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/_compat/shared.py +214 -0
- lib/python3.11/site-packages/fastapi/_compat/v2.py +493 -0
- lib/python3.11/site-packages/fastapi/applications.py +0 -0
- lib/python3.11/site-packages/fastapi/background.py +61 -0
- lib/python3.11/site-packages/fastapi/cli.py +13 -0
- lib/python3.11/site-packages/fastapi/concurrency.py +41 -0
- lib/python3.11/site-packages/fastapi/datastructures.py +186 -0
- lib/python3.11/site-packages/fastapi/dependencies/__init__.py +0 -0
- lib/python3.11/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/dependencies/__pycache__/models.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/dependencies/__pycache__/utils.cpython-311.pyc +0 -0
- lib/python3.11/site-packages/fastapi/dependencies/models.py +193 -0
- lib/python3.11/site-packages/fastapi/dependencies/utils.py +1061 -0
- lib/python3.11/site-packages/fastapi/encoders.py +364 -0
- lib/python3.11/site-packages/fastapi/exception_handlers.py +34 -0
- lib/python3.11/site-packages/fastapi/exceptions.py +256 -0
- lib/python3.11/site-packages/fastapi/logger.py +3 -0
- lib/python3.11/site-packages/fastapi/middleware/__init__.py +1 -0
- lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py +18 -0
- lib/python3.11/site-packages/fastapi/param_functions.py +2460 -0
- lib/python3.11/site-packages/fastapi/params.py +754 -0
- lib/python3.11/site-packages/fastapi/py.typed +0 -0
- lib/python3.11/site-packages/fastapi/requests.py +2 -0
- lib/python3.11/site-packages/fastapi/responses.py +98 -0
- lib/python3.11/site-packages/fastapi/routing.py +0 -0
- lib/python3.11/site-packages/fastapi/sse.py +235 -0
- lib/python3.11/site-packages/fastapi/staticfiles.py +1 -0
- lib/python3.11/site-packages/fastapi/templating.py +1 -0
- lib/python3.11/site-packages/fastapi/testclient.py +1 -0
- lib/python3.11/site-packages/fastapi/types.py +12 -0
- lib/python3.11/site-packages/fastapi/utils.py +136 -0
lib/python3.11/site-packages/_yaml/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a stub package designed to roughly emulate the _yaml
|
| 2 |
+
# extension module, which previously existed as a standalone module
|
| 3 |
+
# and has been moved into the `yaml` package namespace.
|
| 4 |
+
# It does not perfectly mimic its old counterpart, but should get
|
| 5 |
+
# close enough for anyone who's relying on it even when they shouldn't.
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
# in some circumstances, the yaml module we imoprted may be from a different version, so we need
|
| 9 |
+
# to tread carefully when poking at it here (it may not have the attributes we expect)
|
| 10 |
+
if not getattr(yaml, '__with_libyaml__', False):
|
| 11 |
+
from sys import version_info
|
| 12 |
+
|
| 13 |
+
exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
|
| 14 |
+
raise exc("No module named '_yaml'")
|
| 15 |
+
else:
|
| 16 |
+
from yaml._yaml import *
|
| 17 |
+
import warnings
|
| 18 |
+
warnings.warn(
|
| 19 |
+
'The _yaml extension module is now located at yaml._yaml'
|
| 20 |
+
' and its location is subject to change. To use the'
|
| 21 |
+
' LibYAML-based parser and emitter, import from `yaml`:'
|
| 22 |
+
' `from yaml import CLoader as Loader, CDumper as Dumper`.',
|
| 23 |
+
DeprecationWarning
|
| 24 |
+
)
|
| 25 |
+
del warnings
|
| 26 |
+
# Don't `del yaml` here because yaml is actually an existing
|
| 27 |
+
# namespace member of _yaml.
|
| 28 |
+
|
| 29 |
+
__name__ = '_yaml'
|
| 30 |
+
# If the module is top-level (i.e. not a part of any specific package)
|
| 31 |
+
# then the attribute should be set to ''.
|
| 32 |
+
# https://docs.python.org/3.8/library/types.html
|
| 33 |
+
__package__ = ''
|
lib/python3.11/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (939 Bytes). View file
|
|
|
lib/python3.11/site-packages/einops-0.8.2.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
lib/python3.11/site-packages/einops-0.8.2.dist-info/METADATA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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: einops
|
| 3 |
+
Version: 0.8.2
|
| 4 |
+
Summary: A new flavour of deep learning operations
|
| 5 |
+
Project-URL: Homepage, https://github.com/arogozhnikov/einops
|
| 6 |
+
Author: Alex Rogozhnikov
|
| 7 |
+
License: MIT
|
| 8 |
+
License-File: LICENSE
|
| 9 |
+
Keywords: deep learning,einops,machine learning,neural networks,scientific computations,tensor manipulation
|
| 10 |
+
Classifier: Intended Audience :: Science/Research
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Requires-Python: >=3.9
|
| 14 |
+
Description-Content-Type: text/markdown
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
<!--
|
| 18 |
+
<a href='http://arogozhnikov.github.io/images/einops/einops_video.mp4' >
|
| 19 |
+
<div align="center">
|
| 20 |
+
<img src="http://arogozhnikov.github.io/images/einops/einops_video.gif" alt="einops package examples" />
|
| 21 |
+
<br>
|
| 22 |
+
<small><a href='http://arogozhnikov.github.io/images/einops/einops_video.mp4'>This video in high quality (mp4)</a></small>
|
| 23 |
+
<br><br>
|
| 24 |
+
</div>
|
| 25 |
+
</a>
|
| 26 |
+
-->
|
| 27 |
+
|
| 28 |
+
<!-- this link magically rendered as video on github readme, unfortunately not in docs -->
|
| 29 |
+
|
| 30 |
+
https://user-images.githubusercontent.com/6318811/177030658-66f0eb5d-e136-44d8-99c9-86ae298ead5b.mp4
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# einops
|
| 36 |
+
[](https://github.com/arogozhnikov/einops/actions/workflows/run_tests.yml)
|
| 37 |
+
[](https://badge.fury.io/py/einops)
|
| 38 |
+
[](https://einops.rocks/)
|
| 39 |
+

|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Flexible and powerful tensor operations for readable and reliable code. <br />
|
| 43 |
+
Supports numpy, pytorch, tensorflow, jax, and [others](#supported-frameworks).
|
| 44 |
+
|
| 45 |
+
## Recent updates:
|
| 46 |
+
|
| 47 |
+
- 0.8.0: tinygrad backend added, small fixes
|
| 48 |
+
- 0.7.0: no-hassle `torch.compile`, support of [array api standard](https://data-apis.org/array-api/latest/API_specification/index.html) and more
|
| 49 |
+
- 10'000🎉: github reports that more than 10k project use einops
|
| 50 |
+
- einops 0.6.1: paddle backend added
|
| 51 |
+
- einops 0.6 introduces [packing and unpacking](https://github.com/arogozhnikov/einops/blob/main/docs/4-pack-and-unpack.ipynb)
|
| 52 |
+
- einops 0.5: einsum is now a part of einops
|
| 53 |
+
- [Einops paper](https://openreview.net/pdf?id=oapKSVM2bcj) is accepted for oral presentation at ICLR 2022 (yes, it worth reading).
|
| 54 |
+
Talk recordings are [available](https://iclr.cc/virtual/2022/oral/6603)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
<details markdown="1">
|
| 58 |
+
<summary>Previous updates</summary>
|
| 59 |
+
- flax and oneflow backend added
|
| 60 |
+
- torch.jit.script is supported for pytorch layers
|
| 61 |
+
- powerful EinMix added to einops. [Einmix tutorial notebook](https://github.com/arogozhnikov/einops/blob/main/docs/3-einmix-layer.ipynb)
|
| 62 |
+
</details>
|
| 63 |
+
|
| 64 |
+
<!--<div align="center">
|
| 65 |
+
<img src="http://arogozhnikov.github.io/images/einops/einops_logo_350x350.png"
|
| 66 |
+
alt="einops package logo" width="250" height="250" />
|
| 67 |
+
<br><br>
|
| 68 |
+
</div> -->
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
## Tweets
|
| 72 |
+
|
| 73 |
+
> In case you need convincing arguments for setting aside time to learn about einsum and einops...
|
| 74 |
+
[Tim Rocktäschel](https://twitter.com/_rockt/status/1230818967205425152)
|
| 75 |
+
|
| 76 |
+
> Writing better code with PyTorch and einops 👌
|
| 77 |
+
[Andrej Karpathy](https://twitter.com/karpathy/status/1290826075916779520)
|
| 78 |
+
|
| 79 |
+
> Slowly but surely, einops is seeping in to every nook and cranny of my code. If you find yourself shuffling around bazillion dimensional tensors, this might change your life
|
| 80 |
+
[Nasim Rahaman](https://twitter.com/nasim_rahaman/status/1216022614755463169)
|
| 81 |
+
|
| 82 |
+
[More testimonials](https://einops.rocks/pages/testimonials/)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
## Contents
|
| 86 |
+
|
| 87 |
+
- [Installation](#Installation)
|
| 88 |
+
- [Documentation](https://einops.rocks/)
|
| 89 |
+
- [Tutorial](#Tutorials)
|
| 90 |
+
- [API micro-reference](#API)
|
| 91 |
+
- [Why use einops](#Why-use-einops-notation)
|
| 92 |
+
- [Supported frameworks](#Supported-frameworks)
|
| 93 |
+
- [Citing](#Citing)
|
| 94 |
+
- [Repository](https://github.com/arogozhnikov/einops) and [discussions](https://github.com/arogozhnikov/einops/discussions)
|
| 95 |
+
|
| 96 |
+
## Installation <a name="Installation"></a>
|
| 97 |
+
|
| 98 |
+
Plain and simple:
|
| 99 |
+
```bash
|
| 100 |
+
pip install einops
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
(`uv pip install einops` works as well)
|
| 104 |
+
|
| 105 |
+
## Tutorials <a name="Tutorials"></a>
|
| 106 |
+
|
| 107 |
+
Tutorials are the most convenient way to see `einops` in action
|
| 108 |
+
|
| 109 |
+
- part 1: [einops fundamentals](https://github.com/arogozhnikov/einops/blob/main/docs/1-einops-basics.ipynb)
|
| 110 |
+
- part 2: [einops for deep learning](https://github.com/arogozhnikov/einops/blob/main/docs/2-einops-for-deep-learning.ipynb)
|
| 111 |
+
- part 3: [packing and unpacking](https://github.com/arogozhnikov/einops/blob/main/docs/4-pack-and-unpack.ipynb)
|
| 112 |
+
- part 4: [improve pytorch code with einops](http://einops.rocks/pytorch-examples.html)
|
| 113 |
+
|
| 114 |
+
Kapil Sachdeva recorded a small [intro to einops](https://www.youtube.com/watch?v=xGy75Pjsqzo).
|
| 115 |
+
|
| 116 |
+
## API <a name="API"></a>
|
| 117 |
+
|
| 118 |
+
`einops` has a minimalistic yet powerful API.
|
| 119 |
+
|
| 120 |
+
Three core operations provided ([einops tutorial](https://github.com/arogozhnikov/einops/blob/main/docs/)
|
| 121 |
+
shows those cover stacking, reshape, transposition, squeeze/unsqueeze, repeat, tile, concatenate, view and numerous reductions)
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
from einops import rearrange, reduce, repeat
|
| 125 |
+
# rearrange elements according to the pattern
|
| 126 |
+
output_tensor = rearrange(input_tensor, 't b c -> b c t')
|
| 127 |
+
# combine rearrangement and reduction
|
| 128 |
+
output_tensor = reduce(input_tensor, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2)
|
| 129 |
+
# copy along a new axis
|
| 130 |
+
output_tensor = repeat(input_tensor, 'h w -> h w c', c=3)
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
Later additions to the family are `pack` and `unpack` functions (better than stack/split/concatenate):
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
from einops import pack, unpack
|
| 137 |
+
# pack and unpack allow reversibly 'packing' multiple tensors into one.
|
| 138 |
+
# Packed tensors may be of different dimensionality:
|
| 139 |
+
packed, ps = pack([class_token_bc, image_tokens_bhwc, text_tokens_btc], 'b * c')
|
| 140 |
+
class_emb_bc, image_emb_bhwc, text_emb_btc = unpack(transformer(packed), ps, 'b * c')
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Finally, einops provides einsum with a support of multi-lettered names:
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
from einops import einsum, pack, unpack
|
| 147 |
+
# einsum is like ... einsum, generic and flexible dot-product
|
| 148 |
+
# but 1) axes can be multi-lettered 2) pattern goes last 3) works with multiple frameworks
|
| 149 |
+
C = einsum(A, B, 'b t1 head c, b t2 head c -> b head t1 t2')
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
### EinMix
|
| 153 |
+
|
| 154 |
+
`EinMix` is a generic linear layer, perfect for MLP Mixers and similar architectures.
|
| 155 |
+
|
| 156 |
+
### Layers
|
| 157 |
+
|
| 158 |
+
Einops provides layers (`einops` keeps a separate version for each framework) that reflect corresponding functions
|
| 159 |
+
|
| 160 |
+
```python
|
| 161 |
+
from einops.layers.torch import Rearrange, Reduce
|
| 162 |
+
from einops.layers.tensorflow import Rearrange, Reduce
|
| 163 |
+
from einops.layers.flax import Rearrange, Reduce
|
| 164 |
+
from einops.layers.paddle import Rearrange, Reduce
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
<details markdown="1">
|
| 168 |
+
<summary>Example of using layers within a pytorch model</summary>
|
| 169 |
+
Example given for pytorch, but code in other frameworks is almost identical
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
from torch.nn import Sequential, Conv2d, MaxPool2d, Linear, ReLU
|
| 173 |
+
from einops.layers.torch import Rearrange
|
| 174 |
+
|
| 175 |
+
model = Sequential(
|
| 176 |
+
...,
|
| 177 |
+
Conv2d(6, 16, kernel_size=5),
|
| 178 |
+
MaxPool2d(kernel_size=2),
|
| 179 |
+
# flattening without need to write forward
|
| 180 |
+
Rearrange('b c h w -> b (c h w)'),
|
| 181 |
+
Linear(16*5*5, 120),
|
| 182 |
+
ReLU(),
|
| 183 |
+
Linear(120, 10),
|
| 184 |
+
)
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
No more flatten needed!
|
| 188 |
+
|
| 189 |
+
Additionally, torch layers as those are script-able and compile-able.
|
| 190 |
+
Operations [are torch.compile-able](https://github.com/arogozhnikov/einops/wiki/Using-torch.compile-with-einops),
|
| 191 |
+
but not script-able due to limitations of torch.jit.script.
|
| 192 |
+
</details>
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
## Naming <a name="Naming"></a>
|
| 198 |
+
|
| 199 |
+
`einops` stands for Einstein-Inspired Notation for operations
|
| 200 |
+
(though "Einstein operations" is more attractive and easier to remember).
|
| 201 |
+
|
| 202 |
+
Notation was loosely inspired by Einstein summation (in particular by `numpy.einsum` operation).
|
| 203 |
+
|
| 204 |
+
## Why use `einops` notation?! <a name="Why-use-einops-notation"></a>
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
### Semantic information (being verbose in expectations)
|
| 208 |
+
|
| 209 |
+
```python
|
| 210 |
+
y = x.view(x.shape[0], -1)
|
| 211 |
+
y = rearrange(x, 'b c h w -> b (c h w)')
|
| 212 |
+
```
|
| 213 |
+
While these two lines are doing the same job in *some* context,
|
| 214 |
+
the second one provides information about the input and output.
|
| 215 |
+
In other words, `einops` focuses on interface: *what is the input and output*, not *how* the output is computed.
|
| 216 |
+
|
| 217 |
+
The next operation looks similar:
|
| 218 |
+
|
| 219 |
+
```python
|
| 220 |
+
y = rearrange(x, 'time c h w -> time (c h w)')
|
| 221 |
+
```
|
| 222 |
+
but it gives the reader a hint:
|
| 223 |
+
this is not an independent batch of images we are processing,
|
| 224 |
+
but rather a sequence (video).
|
| 225 |
+
|
| 226 |
+
Semantic information makes the code easier to read and maintain.
|
| 227 |
+
|
| 228 |
+
### Convenient checks
|
| 229 |
+
|
| 230 |
+
Reconsider the same example:
|
| 231 |
+
|
| 232 |
+
```python
|
| 233 |
+
y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
|
| 234 |
+
y = rearrange(x, 'b c h w -> b (c h w)')
|
| 235 |
+
```
|
| 236 |
+
The second line checks that the input has four dimensions,
|
| 237 |
+
but you can also specify particular dimensions.
|
| 238 |
+
That's opposed to just writing comments about shapes since comments don't prevent mistakes,
|
| 239 |
+
not tested, and without code review tend to be outdated
|
| 240 |
+
```python
|
| 241 |
+
y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
|
| 242 |
+
y = rearrange(x, 'b c h w -> b (c h w)', c=256, h=19, w=19)
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
### Result is strictly determined
|
| 246 |
+
|
| 247 |
+
Below we have at least two ways to define the depth-to-space operation
|
| 248 |
+
```python
|
| 249 |
+
# depth-to-space
|
| 250 |
+
rearrange(x, 'b c (h h2) (w w2) -> b (c h2 w2) h w', h2=2, w2=2)
|
| 251 |
+
rearrange(x, 'b c (h h2) (w w2) -> b (h2 w2 c) h w', h2=2, w2=2)
|
| 252 |
+
```
|
| 253 |
+
There are at least four more ways to do it. Which one is used by the framework?
|
| 254 |
+
|
| 255 |
+
These details are ignored, since *usually* it makes no difference,
|
| 256 |
+
but it can make a big difference (e.g. if you use grouped convolutions in the next stage),
|
| 257 |
+
and you'd like to specify this in your code.
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
### Uniformity
|
| 261 |
+
|
| 262 |
+
```python
|
| 263 |
+
reduce(x, 'b c (x dx) -> b c x', 'max', dx=2)
|
| 264 |
+
reduce(x, 'b c (x dx) (y dy) -> b c x y', 'max', dx=2, dy=3)
|
| 265 |
+
reduce(x, 'b c (x dx) (y dy) (z dz) -> b c x y z', 'max', dx=2, dy=3, dz=4)
|
| 266 |
+
```
|
| 267 |
+
These examples demonstrated that we don't use separate operations for 1d/2d/3d pooling,
|
| 268 |
+
those are all defined in a uniform way.
|
| 269 |
+
|
| 270 |
+
Space-to-depth and depth-to space are defined in many frameworks but how about width-to-height? Here you go:
|
| 271 |
+
|
| 272 |
+
```python
|
| 273 |
+
rearrange(x, 'b c h (w w2) -> b c (h w2) w', w2=2)
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
### Framework independent behavior
|
| 278 |
+
|
| 279 |
+
Even simple functions are defined differently by different frameworks
|
| 280 |
+
|
| 281 |
+
```python
|
| 282 |
+
y = x.flatten() # or flatten(x)
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
Suppose `x`'s shape was `(3, 4, 5)`, then `y` has shape ...
|
| 286 |
+
|
| 287 |
+
- numpy, pytorch, cupy, chainer, jax: `(60,)`
|
| 288 |
+
- keras, tensorflow.layers, gluon: `(3, 20)`
|
| 289 |
+
|
| 290 |
+
`einops` works the same way in all frameworks.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
### Independence of framework terminology
|
| 294 |
+
|
| 295 |
+
Example: `tile` vs `repeat` causes lots of confusion. To copy image along width:
|
| 296 |
+
```python
|
| 297 |
+
np.tile(image, (1, 2)) # in numpy
|
| 298 |
+
image.repeat(1, 2) # pytorch's repeat ~ numpy's tile
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
With einops you don't need to decipher which axis was repeated:
|
| 302 |
+
```python
|
| 303 |
+
repeat(image, 'h w -> h (tile w)', tile=2) # in numpy
|
| 304 |
+
repeat(image, 'h w -> h (tile w)', tile=2) # in pytorch
|
| 305 |
+
repeat(image, 'h w -> h (tile w)', tile=2) # in tf
|
| 306 |
+
repeat(image, 'h w -> h (tile w)', tile=2) # in jax
|
| 307 |
+
repeat(image, 'h w -> h (tile w)', tile=2) # in cupy
|
| 308 |
+
... (etc.)
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
[Testimonials](https://einops.rocks/pages/testimonials/) provide users' perspective on the same question.
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
## Supported frameworks <a name="Supported-frameworks"></a>
|
| 315 |
+
|
| 316 |
+
Einops works with ...
|
| 317 |
+
|
| 318 |
+
- [numpy](http://www.numpy.org/)
|
| 319 |
+
- [pytorch](https://pytorch.org/)
|
| 320 |
+
- [tensorflow](https://www.tensorflow.org/)
|
| 321 |
+
- [jax](https://github.com/google/jax)
|
| 322 |
+
- [cupy](https://github.com/cupy/cupy)
|
| 323 |
+
- [flax](https://github.com/google/flax) (community)
|
| 324 |
+
- [paddle](https://github.com/PaddlePaddle/Paddle) (community)
|
| 325 |
+
- [oneflow](https://github.com/Oneflow-Inc/oneflow) (community)
|
| 326 |
+
- [tinygrad](https://github.com/tinygrad/tinygrad) (community)
|
| 327 |
+
- [pytensor](https://github.com/pymc-devs/pytensor) (community)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
```python
|
| 332 |
+
from einops import rearrange
|
| 333 |
+
=> from einops.array_api import rearrange
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
But actually it is even better: einops can be used with *any* framework that supports
|
| 337 |
+
[Python array API standard](https://data-apis.org/array-api/latest/API_specification/index.html),
|
| 338 |
+
to name a few:
|
| 339 |
+
|
| 340 |
+
- numpy >= 2.0
|
| 341 |
+
- [MLX](https://github.com/ml-explore/mlx) # yes, einops works with apple's framework
|
| 342 |
+
- [pydata/sparse](https://github.com/pydata/sparse) >= 0.15 # and works with sparse tensors
|
| 343 |
+
- [cubed](https://github.com/cubed-dev/cubed) # and with distributed tensors too
|
| 344 |
+
- [quantco/ndonnx](https://github.com/Quantco/ndonnx)
|
| 345 |
+
- jax
|
| 346 |
+
- cupy
|
| 347 |
+
- dask is supported via [array-api-compat](https://github.com/data-apis/array-api-compat)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
## Development
|
| 351 |
+
|
| 352 |
+
Devcontainer is provided, this environment can be used locally, or on your server,
|
| 353 |
+
or within github codespaces.
|
| 354 |
+
To start with devcontainers in vs code, clone repo, and click 'Reopen in Devcontainer'.
|
| 355 |
+
|
| 356 |
+
Starting from einops 0.8.1, einops distributes tests as a part of package.
|
| 357 |
+
|
| 358 |
+
```bash
|
| 359 |
+
# pip install einops pytest
|
| 360 |
+
python -m einops.tests.run_tests numpy pytorch jax --pip-install
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
`numpy pytorch jax` is an _example_, any subset of testable frameworks can be provided.
|
| 364 |
+
Every framework is tested against numpy, so it is a requirement for tests.
|
| 365 |
+
|
| 366 |
+
Specifying `--pip-install` will install requirements in current virtualenv,
|
| 367 |
+
and should be omitted if dependencies are installed locally.
|
| 368 |
+
|
| 369 |
+
To build/test docs:
|
| 370 |
+
|
| 371 |
+
```bash
|
| 372 |
+
hatch run docs:serve # Serving on http://localhost:8000/
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
## Citing einops <a name="Citing"></a>
|
| 377 |
+
|
| 378 |
+
Please use the following bibtex record
|
| 379 |
+
|
| 380 |
+
```text
|
| 381 |
+
@inproceedings{
|
| 382 |
+
rogozhnikov2022einops,
|
| 383 |
+
title={Einops: Clear and Reliable Tensor Manipulations with Einstein-like Notation},
|
| 384 |
+
author={Alex Rogozhnikov},
|
| 385 |
+
booktitle={International Conference on Learning Representations},
|
| 386 |
+
year={2022},
|
| 387 |
+
url={https://openreview.net/forum?id=oapKSVM2bcj}
|
| 388 |
+
}
|
| 389 |
+
```
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
## Supported python versions
|
| 393 |
+
|
| 394 |
+
`einops` works with python 3.9 or later.
|
lib/python3.11/site-packages/einops-0.8.2.dist-info/RECORD
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
einops-0.8.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
einops-0.8.2.dist-info/METADATA,sha256=C9ZdsENoikT0opYIwculIcky9_928ji72GlEHhUBJlM,13724
|
| 3 |
+
einops-0.8.2.dist-info/RECORD,,
|
| 4 |
+
einops-0.8.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
| 5 |
+
einops-0.8.2.dist-info/licenses/LICENSE,sha256=MNmENkKW9R_67K1LAe4SfpUlDFBokY1LZvyWIGcj5DQ,1073
|
| 6 |
+
einops/__init__.py,sha256=MwPcYWGHKsJE0Uxlhf7YMv_Sf6vu9W9Y98hy1mRM6zk,438
|
| 7 |
+
einops/__pycache__/__init__.cpython-311.pyc,,
|
| 8 |
+
einops/__pycache__/_backends.cpython-311.pyc,,
|
| 9 |
+
einops/__pycache__/_torch_specific.cpython-311.pyc,,
|
| 10 |
+
einops/__pycache__/array_api.cpython-311.pyc,,
|
| 11 |
+
einops/__pycache__/einops.cpython-311.pyc,,
|
| 12 |
+
einops/__pycache__/packing.cpython-311.pyc,,
|
| 13 |
+
einops/__pycache__/parsing.cpython-311.pyc,,
|
| 14 |
+
einops/_backends.py,sha256=v4snGd66fVWeK0M8e3lNJ9j7_qmd8RMRyJVUTQB5slc,22528
|
| 15 |
+
einops/_torch_specific.py,sha256=QXgLFLDIgDa_Iqtv5gcucEeD3LHALYHJhaXRKgC5f4A,4329
|
| 16 |
+
einops/array_api.py,sha256=7mQ-4yhlWtqmtvcTZyI-pmDOSDbk3qpSCExl4-Vm1-o,5236
|
| 17 |
+
einops/einops.py,sha256=vmx5IWde_ePuzrPDLZZVw_-0Qsare1k8YRRaKt5ZL-8,38079
|
| 18 |
+
einops/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 19 |
+
einops/experimental/__pycache__/__init__.cpython-311.pyc,,
|
| 20 |
+
einops/experimental/__pycache__/indexing.cpython-311.pyc,,
|
| 21 |
+
einops/experimental/indexing.py,sha256=yFFflW3-kV6_5PPJU7_jOJsJBCWCWlE4dGlu9gwSPXo,121
|
| 22 |
+
einops/layers/__init__.py,sha256=jijwEY07Yr3rBx8N5zwZ-5qfbl-KX2BcRDK8NJFDaWA,3705
|
| 23 |
+
einops/layers/__pycache__/__init__.cpython-311.pyc,,
|
| 24 |
+
einops/layers/__pycache__/_einmix.cpython-311.pyc,,
|
| 25 |
+
einops/layers/__pycache__/flax.cpython-311.pyc,,
|
| 26 |
+
einops/layers/__pycache__/keras.cpython-311.pyc,,
|
| 27 |
+
einops/layers/__pycache__/oneflow.cpython-311.pyc,,
|
| 28 |
+
einops/layers/__pycache__/paddle.cpython-311.pyc,,
|
| 29 |
+
einops/layers/__pycache__/tensorflow.cpython-311.pyc,,
|
| 30 |
+
einops/layers/__pycache__/torch.cpython-311.pyc,,
|
| 31 |
+
einops/layers/_einmix.py,sha256=MQr6rymfMw-nzFmhvaLCcee0o7Ai8a1lmluxndWDAjU,11075
|
| 32 |
+
einops/layers/flax.py,sha256=Hk7L31wR2BHL63950-0hy3ivw4rc8NkgGW9jn1AKs-8,2518
|
| 33 |
+
einops/layers/keras.py,sha256=jxD9ZgYLWsKMkCIwojbBNSrY6c1pfXYhE2AMZa0pNXA,217
|
| 34 |
+
einops/layers/oneflow.py,sha256=djcKEZRJrWvxTuSsO4jJVZojieKiDPdUpP4SOpg_zTM,1864
|
| 35 |
+
einops/layers/paddle.py,sha256=YCHffUB4ha7wG-xEOeR9XcTPl48Kr57k_nBEx-J6FVA,1907
|
| 36 |
+
einops/layers/tensorflow.py,sha256=MjGApMbkb_gwAdGya7uGfPZ7olyETsRzbwymfJHii9E,3322
|
| 37 |
+
einops/layers/torch.py,sha256=BV-PzjoijGU9RGea1HCFuIMx4yccicz767M0jJDIH6U,2405
|
| 38 |
+
einops/packing.py,sha256=EZeGLgMRD78hB-0e80ubXvWHukh0_O_wJCf0Hbbdylo,7660
|
| 39 |
+
einops/parsing.py,sha256=vNPYcAs54-KLX1RtbkypGpsSpujzVkj_dQkZlUinLYw,6805
|
| 40 |
+
einops/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 41 |
+
einops/tests/__init__.py,sha256=CpSdrOGBSspTwuG6cAsYMGAwkTq0VuIBrehM7K-SYwU,3531
|
| 42 |
+
einops/tests/__pycache__/__init__.cpython-311.pyc,,
|
| 43 |
+
einops/tests/__pycache__/run_tests.cpython-311.pyc,,
|
| 44 |
+
einops/tests/__pycache__/test_einsum.cpython-311.pyc,,
|
| 45 |
+
einops/tests/__pycache__/test_examples.cpython-311.pyc,,
|
| 46 |
+
einops/tests/__pycache__/test_layers.cpython-311.pyc,,
|
| 47 |
+
einops/tests/__pycache__/test_ops.cpython-311.pyc,,
|
| 48 |
+
einops/tests/__pycache__/test_other.cpython-311.pyc,,
|
| 49 |
+
einops/tests/__pycache__/test_packing.cpython-311.pyc,,
|
| 50 |
+
einops/tests/__pycache__/test_parsing.cpython-311.pyc,,
|
| 51 |
+
einops/tests/run_tests.py,sha256=efJ2apHPOw1BKNIv5qZSNjHpgjSv0rJ4v9hbPbE7yNE,3072
|
| 52 |
+
einops/tests/test_einsum.py,sha256=Nycwg4a-4_Vz7l5f7mj2KIQ7QVs8P2SQIy1rnDcMOG8,11022
|
| 53 |
+
einops/tests/test_examples.py,sha256=6VVkHgov6hpEyoUGbMzFvRfoWTdP1Wr8RPji7G4pPlw,11510
|
| 54 |
+
einops/tests/test_layers.py,sha256=m8RqmBojvVMgr_ET6mhcGpbfYPasg60jUYux7ZlXhSM,18667
|
| 55 |
+
einops/tests/test_ops.py,sha256=4nxEGJWrmEG6cctYHGYuVVdEs5nUN9ziH7ukQYar44M,26884
|
| 56 |
+
einops/tests/test_other.py,sha256=vkWSJr7sn-COewksivTPaLe-GAmzLt7IEZF9TMnt360,13521
|
| 57 |
+
einops/tests/test_packing.py,sha256=AIBNiy8RftTj8dLv1AdNijkTXfrjCOTSw43fuD6Pfjc,10408
|
| 58 |
+
einops/tests/test_parsing.py,sha256=-YAJeJlhDb3U6xYIDRrtm6p4MSNWogeH6l3-np1wUCA,4389
|
lib/python3.11/site-packages/einops-0.8.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.27.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
lib/python3.11/site-packages/einops-0.8.2.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2018 Alex Rogozhnikov
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
lib/python3.11/site-packages/einops/__pycache__/packing.cpython-311.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|
lib/python3.11/site-packages/einops/__pycache__/parsing.cpython-311.pyc
ADDED
|
Binary file (8.33 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/SKILL.md
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
name: fastapi
|
| 3 |
+
description: FastAPI best practices and conventions. Use when working with FastAPI APIs and Pydantic models for them. Keeps FastAPI code clean and up to date with the latest features and patterns, updated with new versions. Write new code or refactor and update old code.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# FastAPI
|
| 7 |
+
|
| 8 |
+
Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.
|
| 9 |
+
|
| 10 |
+
## Use the `fastapi` CLI
|
| 11 |
+
|
| 12 |
+
Run the development server on localhost with reload:
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
fastapi dev
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Run the production server:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
fastapi run
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
### Add an entrypoint in `pyproject.toml`
|
| 26 |
+
|
| 27 |
+
FastAPI CLI will read the entrypoint in `pyproject.toml` to know where the FastAPI app is declared.
|
| 28 |
+
|
| 29 |
+
```toml
|
| 30 |
+
[tool.fastapi]
|
| 31 |
+
entrypoint = "my_app.main:app"
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
### Use `fastapi` with a path
|
| 35 |
+
|
| 36 |
+
When adding the entrypoint to `pyproject.toml` is not possible, or the user explicitly asks not to, or it's running an independent small app, you can pass the app file path to the `fastapi` command:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
fastapi dev my_app/main.py
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Prefer to set the entrypoint in `pyproject.toml` when possible.
|
| 43 |
+
|
| 44 |
+
## Use `Annotated`
|
| 45 |
+
|
| 46 |
+
Always prefer the `Annotated` style for parameter and dependency declarations.
|
| 47 |
+
|
| 48 |
+
It keeps the function signatures working in other contexts, respects the types, allows reusability.
|
| 49 |
+
|
| 50 |
+
### In Parameter Declarations
|
| 51 |
+
|
| 52 |
+
Use `Annotated` for parameter declarations, including `Path`, `Query`, `Header`, etc.:
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
from typing import Annotated
|
| 56 |
+
|
| 57 |
+
from fastapi import FastAPI, Path, Query
|
| 58 |
+
|
| 59 |
+
app = FastAPI()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.get("/items/{item_id}")
|
| 63 |
+
async def read_item(
|
| 64 |
+
item_id: Annotated[int, Path(ge=1, description="The item ID")],
|
| 65 |
+
q: Annotated[str | None, Query(max_length=50)] = None,
|
| 66 |
+
):
|
| 67 |
+
return {"message": "Hello World"}
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
instead of:
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
# DO NOT DO THIS
|
| 74 |
+
@app.get("/items/{item_id}")
|
| 75 |
+
async def read_item(
|
| 76 |
+
item_id: int = Path(ge=1, description="The item ID"),
|
| 77 |
+
q: str | None = Query(default=None, max_length=50),
|
| 78 |
+
):
|
| 79 |
+
return {"message": "Hello World"}
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### For Dependencies
|
| 83 |
+
|
| 84 |
+
Use `Annotated` for dependencies with `Depends()`.
|
| 85 |
+
|
| 86 |
+
Unless asked not to, create a new type alias for the dependency to allow re-using it.
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
from typing import Annotated
|
| 90 |
+
|
| 91 |
+
from fastapi import Depends, FastAPI
|
| 92 |
+
|
| 93 |
+
app = FastAPI()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_current_user():
|
| 97 |
+
return {"username": "johndoe"}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
CurrentUserDep = Annotated[dict, Depends(get_current_user)]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@app.get("/items/")
|
| 104 |
+
async def read_item(current_user: CurrentUserDep):
|
| 105 |
+
return {"message": "Hello World"}
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
instead of:
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
# DO NOT DO THIS
|
| 112 |
+
@app.get("/items/")
|
| 113 |
+
async def read_item(current_user: dict = Depends(get_current_user)):
|
| 114 |
+
return {"message": "Hello World"}
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
## Do not use Ellipsis for *path operations* or Pydantic models
|
| 118 |
+
|
| 119 |
+
Do not use `...` as a default value for required parameters, it's not needed and not recommended.
|
| 120 |
+
|
| 121 |
+
Do this, without Ellipsis (`...`):
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
from typing import Annotated
|
| 125 |
+
|
| 126 |
+
from fastapi import FastAPI, Query
|
| 127 |
+
from pydantic import BaseModel, Field
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class Item(BaseModel):
|
| 131 |
+
name: str
|
| 132 |
+
description: str | None = None
|
| 133 |
+
price: float = Field(gt=0)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
app = FastAPI()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@app.post("/items/")
|
| 140 |
+
async def create_item(item: Item, project_id: Annotated[int, Query()]): ...
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
instead of this:
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
# DO NOT DO THIS
|
| 147 |
+
class Item(BaseModel):
|
| 148 |
+
name: str = ...
|
| 149 |
+
description: str | None = None
|
| 150 |
+
price: float = Field(..., gt=0)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
app = FastAPI()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@app.post("/items/")
|
| 157 |
+
async def create_item(item: Item, project_id: Annotated[int, Query(...)]): ...
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
## Return Type or Response Model
|
| 161 |
+
|
| 162 |
+
When possible, include a return type. It will be used to validate, filter, document, and serialize the response.
|
| 163 |
+
|
| 164 |
+
```python
|
| 165 |
+
from fastapi import FastAPI
|
| 166 |
+
from pydantic import BaseModel
|
| 167 |
+
|
| 168 |
+
app = FastAPI()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class Item(BaseModel):
|
| 172 |
+
name: str
|
| 173 |
+
description: str | None = None
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@app.get("/items/me")
|
| 177 |
+
async def get_item() -> Item:
|
| 178 |
+
return Item(name="Plumbus", description="All-purpose home device")
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
**Important**: Return types or response models are what filter data ensuring no sensitive information is exposed. And they are used to serialize data with Pydantic (in Rust), this is the main idea that can increase response performance.
|
| 182 |
+
|
| 183 |
+
The return type doesn't have to be a Pydantic model, it could be a different type, like a list of integers, or a dict, etc.
|
| 184 |
+
|
| 185 |
+
### When to use `response_model` instead
|
| 186 |
+
|
| 187 |
+
If the return type is not the same as the type that you want to use to validate, filter, or serialize, use the `response_model` parameter on the decorator instead.
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
from typing import Any
|
| 191 |
+
|
| 192 |
+
from fastapi import FastAPI
|
| 193 |
+
from pydantic import BaseModel
|
| 194 |
+
|
| 195 |
+
app = FastAPI()
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Item(BaseModel):
|
| 199 |
+
name: str
|
| 200 |
+
description: str | None = None
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@app.get("/items/me", response_model=Item)
|
| 204 |
+
async def get_item() -> Any:
|
| 205 |
+
return {"name": "Foo", "description": "A very nice Item"}
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
This can be particularly useful when filtering data to expose only the public fields and avoid exposing sensitive information.
|
| 209 |
+
|
| 210 |
+
```python
|
| 211 |
+
from typing import Any
|
| 212 |
+
|
| 213 |
+
from fastapi import FastAPI
|
| 214 |
+
from pydantic import BaseModel
|
| 215 |
+
|
| 216 |
+
app = FastAPI()
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class InternalItem(BaseModel):
|
| 220 |
+
name: str
|
| 221 |
+
description: str | None = None
|
| 222 |
+
secret_key: str
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Item(BaseModel):
|
| 226 |
+
name: str
|
| 227 |
+
description: str | None = None
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@app.get("/items/me", response_model=Item)
|
| 231 |
+
async def get_item() -> Any:
|
| 232 |
+
item = InternalItem(
|
| 233 |
+
name="Foo", description="A very nice Item", secret_key="supersecret"
|
| 234 |
+
)
|
| 235 |
+
return item
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
## Performance
|
| 239 |
+
|
| 240 |
+
Do not use `ORJSONResponse` or `UJSONResponse`, they are deprecated.
|
| 241 |
+
|
| 242 |
+
Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.
|
| 243 |
+
|
| 244 |
+
## Including Routers
|
| 245 |
+
|
| 246 |
+
When declaring routers, prefer to add router level parameters like prefix, tags, etc. to the router itself, instead of in `include_router()`.
|
| 247 |
+
|
| 248 |
+
Do this:
|
| 249 |
+
|
| 250 |
+
```python
|
| 251 |
+
from fastapi import APIRouter, FastAPI
|
| 252 |
+
|
| 253 |
+
app = FastAPI()
|
| 254 |
+
|
| 255 |
+
router = APIRouter(prefix="/items", tags=["items"])
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@router.get("/")
|
| 259 |
+
async def list_items():
|
| 260 |
+
return []
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# In main.py
|
| 264 |
+
app.include_router(router)
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
instead of this:
|
| 268 |
+
|
| 269 |
+
```python
|
| 270 |
+
# DO NOT DO THIS
|
| 271 |
+
from fastapi import APIRouter, FastAPI
|
| 272 |
+
|
| 273 |
+
app = FastAPI()
|
| 274 |
+
|
| 275 |
+
router = APIRouter()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@router.get("/")
|
| 279 |
+
async def list_items():
|
| 280 |
+
return []
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# In main.py
|
| 284 |
+
app.include_router(router, prefix="/items", tags=["items"])
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
There could be exceptions, but try to follow this convention.
|
| 288 |
+
|
| 289 |
+
Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
|
| 290 |
+
|
| 291 |
+
## Dependency Injection
|
| 292 |
+
|
| 293 |
+
See [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies.
|
| 294 |
+
|
| 295 |
+
Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup (with `yield`), or is shared across endpoints.
|
| 296 |
+
|
| 297 |
+
Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
|
| 298 |
+
|
| 299 |
+
## Async vs Sync *path operations*
|
| 300 |
+
|
| 301 |
+
Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await (it's called with `await`) or that doesn't block.
|
| 302 |
+
|
| 303 |
+
```python
|
| 304 |
+
from fastapi import FastAPI
|
| 305 |
+
|
| 306 |
+
app = FastAPI()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# Use async def when calling async code
|
| 310 |
+
@app.get("/async-items/")
|
| 311 |
+
async def read_async_items():
|
| 312 |
+
data = await some_async_library.fetch_items()
|
| 313 |
+
return data
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# Use plain def when calling blocking/sync code or when in doubt
|
| 317 |
+
@app.get("/items/")
|
| 318 |
+
def read_items():
|
| 319 |
+
data = some_blocking_library.fetch_items()
|
| 320 |
+
return data
|
| 321 |
+
```
|
| 322 |
+
|
| 323 |
+
In case of doubt, or by default, use regular `def` functions, those will be run in a threadpool so they don't block the event loop.
|
| 324 |
+
|
| 325 |
+
The same rules apply to dependencies.
|
| 326 |
+
|
| 327 |
+
Make sure blocking code is not run inside of `async` functions. The logic will work, but will damage the performance heavily.
|
| 328 |
+
|
| 329 |
+
When needing to mix blocking and async code, see Asyncer in [the other tools reference](references/other-tools.md).
|
| 330 |
+
|
| 331 |
+
## Streaming (JSON Lines, SSE, bytes)
|
| 332 |
+
|
| 333 |
+
See [the streaming reference](references/streaming.md) for JSON Lines, Server-Sent Events (`EventSourceResponse`, `ServerSentEvent`), and byte streaming (`StreamingResponse`) patterns.
|
| 334 |
+
|
| 335 |
+
## Tooling
|
| 336 |
+
|
| 337 |
+
See [the other tools reference](references/other-tools.md) for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
|
| 338 |
+
|
| 339 |
+
## Other Libraries
|
| 340 |
+
|
| 341 |
+
See [the other tools reference](references/other-tools.md) for details on other libraries:
|
| 342 |
+
|
| 343 |
+
* Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.
|
| 344 |
+
* SQLModel for working with SQL databases, prefer it over SQLAlchemy.
|
| 345 |
+
* HTTPX for interacting with HTTP (other APIs), prefer it over Requests.
|
| 346 |
+
|
| 347 |
+
## Do not use Pydantic RootModels
|
| 348 |
+
|
| 349 |
+
Do not use Pydantic `RootModel`, instead use regular type annotations with `Annotated` and Pydantic validation utilities.
|
| 350 |
+
|
| 351 |
+
For example, for a list with validations you could do:
|
| 352 |
+
|
| 353 |
+
```python
|
| 354 |
+
from typing import Annotated
|
| 355 |
+
|
| 356 |
+
from fastapi import Body, FastAPI
|
| 357 |
+
from pydantic import Field
|
| 358 |
+
|
| 359 |
+
app = FastAPI()
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@app.post("/items/")
|
| 363 |
+
async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):
|
| 364 |
+
return items
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
instead of:
|
| 368 |
+
|
| 369 |
+
```python
|
| 370 |
+
# DO NOT DO THIS
|
| 371 |
+
from typing import Annotated
|
| 372 |
+
|
| 373 |
+
from fastapi import FastAPI
|
| 374 |
+
from pydantic import Field, RootModel
|
| 375 |
+
|
| 376 |
+
app = FastAPI()
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class ItemList(RootModel[Annotated[list[int], Field(min_length=1)]]):
|
| 380 |
+
pass
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
@app.post("/items/")
|
| 384 |
+
async def create_items(items: ItemList):
|
| 385 |
+
return items
|
| 386 |
+
|
| 387 |
+
```
|
| 388 |
+
|
| 389 |
+
FastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so that types can work as normally and there's no need for the custom logic and types in RootModels.
|
| 390 |
+
|
| 391 |
+
## Use one HTTP operation per function
|
| 392 |
+
|
| 393 |
+
Don't mix HTTP operations in a single function, having one function per HTTP operation helps separate concerns and organize the code.
|
| 394 |
+
|
| 395 |
+
Do this:
|
| 396 |
+
|
| 397 |
+
```python
|
| 398 |
+
from fastapi import FastAPI
|
| 399 |
+
from pydantic import BaseModel
|
| 400 |
+
|
| 401 |
+
app = FastAPI()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class Item(BaseModel):
|
| 405 |
+
name: str
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@app.get("/items/")
|
| 409 |
+
async def list_items():
|
| 410 |
+
return []
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@app.post("/items/")
|
| 414 |
+
async def create_item(item: Item):
|
| 415 |
+
return item
|
| 416 |
+
```
|
| 417 |
+
|
| 418 |
+
instead of this:
|
| 419 |
+
|
| 420 |
+
```python
|
| 421 |
+
# DO NOT DO THIS
|
| 422 |
+
from fastapi import FastAPI, Request
|
| 423 |
+
from pydantic import BaseModel
|
| 424 |
+
|
| 425 |
+
app = FastAPI()
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class Item(BaseModel):
|
| 429 |
+
name: str
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
@app.api_route("/items/", methods=["GET", "POST"])
|
| 433 |
+
async def handle_items(request: Request):
|
| 434 |
+
if request.method == "GET":
|
| 435 |
+
return []
|
| 436 |
+
```
|
lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/dependencies.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dependency Injection
|
| 2 |
+
|
| 3 |
+
Use dependencies when:
|
| 4 |
+
|
| 5 |
+
* They can't be declared in Pydantic validation and require additional logic
|
| 6 |
+
* The logic depends on external resources or could block in any other way
|
| 7 |
+
* Other dependencies need their results (it's a sub-dependency)
|
| 8 |
+
* The logic can be shared by multiple endpoints to do things like error early, authentication, etc.
|
| 9 |
+
* They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield`
|
| 10 |
+
* Their logic needs input data from the request, like headers, query parameters, etc.
|
| 11 |
+
|
| 12 |
+
## Dependencies with `yield` and `scope`
|
| 13 |
+
|
| 14 |
+
When using dependencies with `yield`, they can have a `scope` that defines when the exit code is run.
|
| 15 |
+
|
| 16 |
+
Use the default scope `"request"` to run the exit code after the response is sent back.
|
| 17 |
+
|
| 18 |
+
```python
|
| 19 |
+
from typing import Annotated
|
| 20 |
+
|
| 21 |
+
from fastapi import Depends, FastAPI
|
| 22 |
+
|
| 23 |
+
app = FastAPI()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_db():
|
| 27 |
+
db = DBSession()
|
| 28 |
+
try:
|
| 29 |
+
yield db
|
| 30 |
+
finally:
|
| 31 |
+
db.close()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
DBDep = Annotated[DBSession, Depends(get_db)]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@app.get("/items/")
|
| 38 |
+
async def read_items(db: DBDep):
|
| 39 |
+
return db.query(Item).all()
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Use the scope `"function"` when they should run the exit code after the response data is generated but before the response is sent back to the client.
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from typing import Annotated
|
| 46 |
+
|
| 47 |
+
from fastapi import Depends, FastAPI
|
| 48 |
+
|
| 49 |
+
app = FastAPI()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_username():
|
| 53 |
+
try:
|
| 54 |
+
yield "Rick"
|
| 55 |
+
finally:
|
| 56 |
+
print("Cleanup up before response is sent")
|
| 57 |
+
|
| 58 |
+
UserNameDep = Annotated[str, Depends(get_username, scope="function")]
|
| 59 |
+
|
| 60 |
+
@app.get("/users/me")
|
| 61 |
+
def get_user_me(username: UserNameDep):
|
| 62 |
+
return username
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## Class Dependencies
|
| 66 |
+
|
| 67 |
+
Avoid creating class dependencies when possible.
|
| 68 |
+
|
| 69 |
+
If a class is needed, instead create a regular function dependency that returns a class instance.
|
| 70 |
+
|
| 71 |
+
Do this:
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
from dataclasses import dataclass
|
| 75 |
+
from typing import Annotated
|
| 76 |
+
|
| 77 |
+
from fastapi import Depends, FastAPI
|
| 78 |
+
|
| 79 |
+
app = FastAPI()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass
|
| 83 |
+
class DatabasePaginator:
|
| 84 |
+
offset: int = 0
|
| 85 |
+
limit: int = 100
|
| 86 |
+
q: str | None = None
|
| 87 |
+
|
| 88 |
+
def get_page(self) -> dict:
|
| 89 |
+
# Simulate a page of data
|
| 90 |
+
return {
|
| 91 |
+
"offset": self.offset,
|
| 92 |
+
"limit": self.limit,
|
| 93 |
+
"q": self.q,
|
| 94 |
+
"items": [],
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def get_db_paginator(
|
| 99 |
+
offset: int = 0, limit: int = 100, q: str | None = None
|
| 100 |
+
) -> DatabasePaginator:
|
| 101 |
+
return DatabasePaginator(offset=offset, limit=limit, q=q)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
PaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@app.get("/items/")
|
| 108 |
+
async def read_items(paginator: PaginatorDep):
|
| 109 |
+
return paginator.get_page()
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
instead of this:
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
# DO NOT DO THIS
|
| 116 |
+
from typing import Annotated
|
| 117 |
+
|
| 118 |
+
from fastapi import Depends, FastAPI
|
| 119 |
+
|
| 120 |
+
app = FastAPI()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class DatabasePaginator:
|
| 124 |
+
def __init__(self, offset: int = 0, limit: int = 100, q: str | None = None):
|
| 125 |
+
self.offset = offset
|
| 126 |
+
self.limit = limit
|
| 127 |
+
self.q = q
|
| 128 |
+
|
| 129 |
+
def get_page(self) -> dict:
|
| 130 |
+
# Simulate a page of data
|
| 131 |
+
return {
|
| 132 |
+
"offset": self.offset,
|
| 133 |
+
"limit": self.limit,
|
| 134 |
+
"q": self.q,
|
| 135 |
+
"items": [],
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@app.get("/items/")
|
| 140 |
+
async def read_items(paginator: Annotated[DatabasePaginator, Depends()]):
|
| 141 |
+
return paginator.get_page()
|
| 142 |
+
```
|
lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/other-tools.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Other Tools
|
| 2 |
+
|
| 3 |
+
## uv
|
| 4 |
+
|
| 5 |
+
If uv is available, use it to manage dependencies.
|
| 6 |
+
|
| 7 |
+
## Ruff
|
| 8 |
+
|
| 9 |
+
If Ruff is available, use it to lint and format the code. Consider enabling the FastAPI rules.
|
| 10 |
+
|
| 11 |
+
## ty
|
| 12 |
+
|
| 13 |
+
If ty is available, use it to check types.
|
| 14 |
+
|
| 15 |
+
## Asyncer
|
| 16 |
+
|
| 17 |
+
When needing to run blocking code inside of async functions, or async code inside of blocking functions, suggest using Asyncer.
|
| 18 |
+
|
| 19 |
+
Prefer it over AnyIO or asyncio.
|
| 20 |
+
|
| 21 |
+
Install:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
uv add asyncer
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Run blocking sync code inside of async with `asyncify()`:
|
| 28 |
+
|
| 29 |
+
```python
|
| 30 |
+
from asyncer import asyncify
|
| 31 |
+
from fastapi import FastAPI
|
| 32 |
+
|
| 33 |
+
app = FastAPI()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def do_blocking_work(name: str) -> str:
|
| 37 |
+
# Some blocking I/O operation
|
| 38 |
+
return f"Hello {name}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@app.get("/items/")
|
| 42 |
+
async def read_items():
|
| 43 |
+
result = await asyncify(do_blocking_work)(name="World")
|
| 44 |
+
return {"message": result}
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
And run async code inside of blocking sync code with `syncify()`:
|
| 48 |
+
|
| 49 |
+
```python
|
| 50 |
+
from asyncer import syncify
|
| 51 |
+
from fastapi import FastAPI
|
| 52 |
+
|
| 53 |
+
app = FastAPI()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
async def do_async_work(name: str) -> str:
|
| 57 |
+
return f"Hello {name}"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.get("/items/")
|
| 61 |
+
def read_items():
|
| 62 |
+
result = syncify(do_async_work)(name="World")
|
| 63 |
+
return {"message": result}
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## SQLModel for SQL databases
|
| 67 |
+
|
| 68 |
+
When working with SQL databases, prefer using SQLModel as it is integrated with Pydantic and will allow declaring data validation with the same models.
|
| 69 |
+
|
| 70 |
+
Prefer it over SQLAlchemy.
|
| 71 |
+
|
| 72 |
+
## HTTPX
|
| 73 |
+
|
| 74 |
+
Use HTTPX for handling HTTP communication (e.g. with other APIs). It support sync and async usage.
|
| 75 |
+
|
| 76 |
+
Prefer it over Requests.
|
lib/python3.11/site-packages/fastapi/.agents/skills/fastapi/references/streaming.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Streaming
|
| 2 |
+
|
| 3 |
+
## Stream JSON Lines
|
| 4 |
+
|
| 5 |
+
To stream JSON Lines, declare the return type and use `yield` to return the data.
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
@app.get("/items/stream")
|
| 9 |
+
async def stream_items() -> AsyncIterable[Item]:
|
| 10 |
+
for item in items:
|
| 11 |
+
yield item
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
## Server-Sent Events (SSE)
|
| 15 |
+
|
| 16 |
+
To stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint.
|
| 17 |
+
|
| 18 |
+
Plain objects are automatically JSON-serialized as `data:` fields, declare the return type so the serialization is done by Pydantic:
|
| 19 |
+
|
| 20 |
+
```python
|
| 21 |
+
from collections.abc import AsyncIterable
|
| 22 |
+
|
| 23 |
+
from fastapi import FastAPI
|
| 24 |
+
from fastapi.sse import EventSourceResponse
|
| 25 |
+
from pydantic import BaseModel
|
| 26 |
+
|
| 27 |
+
app = FastAPI()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Item(BaseModel):
|
| 31 |
+
name: str
|
| 32 |
+
price: float
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@app.get("/items/stream", response_class=EventSourceResponse)
|
| 36 |
+
async def stream_items() -> AsyncIterable[Item]:
|
| 37 |
+
yield Item(name="Plumbus", price=32.99)
|
| 38 |
+
yield Item(name="Portal Gun", price=999.99)
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
For full control over SSE fields (`event`, `id`, `retry`, `comment`), yield `ServerSentEvent` instances:
|
| 42 |
+
|
| 43 |
+
```python
|
| 44 |
+
from collections.abc import AsyncIterable
|
| 45 |
+
|
| 46 |
+
from fastapi import FastAPI
|
| 47 |
+
from fastapi.sse import EventSourceResponse, ServerSentEvent
|
| 48 |
+
|
| 49 |
+
app = FastAPI()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@app.get("/events", response_class=EventSourceResponse)
|
| 53 |
+
async def stream_events() -> AsyncIterable[ServerSentEvent]:
|
| 54 |
+
yield ServerSentEvent(data={"status": "started"}, event="status", id="1")
|
| 55 |
+
yield ServerSentEvent(data={"progress": 50}, event="progress", id="2")
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Use `raw_data` instead of `data` to send pre-formatted strings without JSON encoding:
|
| 59 |
+
|
| 60 |
+
```python
|
| 61 |
+
yield ServerSentEvent(raw_data="plain text line", event="log")
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
## Stream bytes
|
| 65 |
+
|
| 66 |
+
To stream bytes, declare a `response_class=` of `StreamingResponse` or a sub-class, and use `yield` to return the data.
|
| 67 |
+
|
| 68 |
+
```python
|
| 69 |
+
from fastapi import FastAPI
|
| 70 |
+
from fastapi.responses import StreamingResponse
|
| 71 |
+
from app.utils import read_image
|
| 72 |
+
|
| 73 |
+
app = FastAPI()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PNGStreamingResponse(StreamingResponse):
|
| 77 |
+
media_type = "image/png"
|
| 78 |
+
|
| 79 |
+
@app.get("/image", response_class=PNGStreamingResponse)
|
| 80 |
+
def stream_image_no_async_no_annotation():
|
| 81 |
+
with read_image() as image_file:
|
| 82 |
+
yield from image_file
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
prefer this over returning a `StreamingResponse` directly:
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
# DO NOT DO THIS
|
| 89 |
+
|
| 90 |
+
import anyio
|
| 91 |
+
from fastapi import FastAPI
|
| 92 |
+
from fastapi.responses import StreamingResponse
|
| 93 |
+
from app.utils import read_image
|
| 94 |
+
|
| 95 |
+
app = FastAPI()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class PNGStreamingResponse(StreamingResponse):
|
| 99 |
+
media_type = "image/png"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@app.get("/")
|
| 103 |
+
async def main():
|
| 104 |
+
return PNGStreamingResponse(read_image())
|
| 105 |
+
```
|
lib/python3.11/site-packages/fastapi/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.136.3"
|
| 4 |
+
|
| 5 |
+
from starlette import status as status
|
| 6 |
+
|
| 7 |
+
from .applications import FastAPI as FastAPI
|
| 8 |
+
from .background import BackgroundTasks as BackgroundTasks
|
| 9 |
+
from .datastructures import UploadFile as UploadFile
|
| 10 |
+
from .exceptions import HTTPException as HTTPException
|
| 11 |
+
from .exceptions import WebSocketException as WebSocketException
|
| 12 |
+
from .param_functions import Body as Body
|
| 13 |
+
from .param_functions import Cookie as Cookie
|
| 14 |
+
from .param_functions import Depends as Depends
|
| 15 |
+
from .param_functions import File as File
|
| 16 |
+
from .param_functions import Form as Form
|
| 17 |
+
from .param_functions import Header as Header
|
| 18 |
+
from .param_functions import Path as Path
|
| 19 |
+
from .param_functions import Query as Query
|
| 20 |
+
from .param_functions import Security as Security
|
| 21 |
+
from .requests import Request as Request
|
| 22 |
+
from .responses import Response as Response
|
| 23 |
+
from .routing import APIRouter as APIRouter
|
| 24 |
+
from .websockets import WebSocket as WebSocket
|
| 25 |
+
from .websockets import WebSocketDisconnect as WebSocketDisconnect
|
lib/python3.11/site-packages/fastapi/__main__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi.cli import main
|
| 2 |
+
|
| 3 |
+
main()
|
lib/python3.11/site-packages/fastapi/_compat/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE
|
| 2 |
+
from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1
|
| 3 |
+
from .shared import field_annotation_is_scalar as field_annotation_is_scalar
|
| 4 |
+
from .shared import (
|
| 5 |
+
field_annotation_is_scalar_sequence as field_annotation_is_scalar_sequence,
|
| 6 |
+
)
|
| 7 |
+
from .shared import field_annotation_is_sequence as field_annotation_is_sequence
|
| 8 |
+
from .shared import (
|
| 9 |
+
is_bytes_or_nonable_bytes_annotation as is_bytes_or_nonable_bytes_annotation,
|
| 10 |
+
)
|
| 11 |
+
from .shared import is_bytes_sequence_annotation as is_bytes_sequence_annotation
|
| 12 |
+
from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance
|
| 13 |
+
from .shared import (
|
| 14 |
+
is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation,
|
| 15 |
+
)
|
| 16 |
+
from .shared import (
|
| 17 |
+
is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation,
|
| 18 |
+
)
|
| 19 |
+
from .shared import lenient_issubclass as lenient_issubclass
|
| 20 |
+
from .shared import sequence_types as sequence_types
|
| 21 |
+
from .shared import value_is_sequence as value_is_sequence
|
| 22 |
+
from .v2 import ModelField as ModelField
|
| 23 |
+
from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError
|
| 24 |
+
from .v2 import RequiredParam as RequiredParam
|
| 25 |
+
from .v2 import Undefined as Undefined
|
| 26 |
+
from .v2 import Url as Url
|
| 27 |
+
from .v2 import copy_field_info as copy_field_info
|
| 28 |
+
from .v2 import create_body_model as create_body_model
|
| 29 |
+
from .v2 import evaluate_forwardref as evaluate_forwardref
|
| 30 |
+
from .v2 import get_cached_model_fields as get_cached_model_fields
|
| 31 |
+
from .v2 import get_definitions as get_definitions
|
| 32 |
+
from .v2 import get_flat_models_from_fields as get_flat_models_from_fields
|
| 33 |
+
from .v2 import get_missing_field_error as get_missing_field_error
|
| 34 |
+
from .v2 import get_model_name_map as get_model_name_map
|
| 35 |
+
from .v2 import get_schema_from_model_field as get_schema_from_model_field
|
| 36 |
+
from .v2 import is_scalar_field as is_scalar_field
|
| 37 |
+
from .v2 import serialize_sequence_value as serialize_sequence_value
|
| 38 |
+
from .v2 import (
|
| 39 |
+
with_info_plain_validator_function as with_info_plain_validator_function,
|
| 40 |
+
)
|
lib/python3.11/site-packages/fastapi/_compat/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (2.14 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/_compat/__pycache__/shared.cpython-311.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/_compat/__pycache__/v2.cpython-311.pyc
ADDED
|
Binary file (23.1 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/_compat/shared.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import types
|
| 2 |
+
import typing
|
| 3 |
+
import warnings
|
| 4 |
+
from collections import deque
|
| 5 |
+
from collections.abc import Mapping, Sequence
|
| 6 |
+
from dataclasses import is_dataclass
|
| 7 |
+
from typing import (
|
| 8 |
+
Annotated,
|
| 9 |
+
Any,
|
| 10 |
+
TypeGuard,
|
| 11 |
+
TypeVar,
|
| 12 |
+
Union,
|
| 13 |
+
get_args,
|
| 14 |
+
get_origin,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from fastapi.types import UnionType
|
| 18 |
+
from pydantic import BaseModel
|
| 19 |
+
from pydantic.version import VERSION as PYDANTIC_VERSION
|
| 20 |
+
from starlette.datastructures import UploadFile
|
| 21 |
+
|
| 22 |
+
_T = TypeVar("_T")
|
| 23 |
+
|
| 24 |
+
# Copy from Pydantic: pydantic/_internal/_typing_extra.py
|
| 25 |
+
WithArgsTypes: tuple[Any, ...] = (
|
| 26 |
+
typing._GenericAlias, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
|
| 27 |
+
types.GenericAlias,
|
| 28 |
+
types.UnionType,
|
| 29 |
+
) # pyright: ignore[reportAttributeAccessIssue]
|
| 30 |
+
|
| 31 |
+
PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2])
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
sequence_annotation_to_type = {
|
| 35 |
+
Sequence: list,
|
| 36 |
+
list: list,
|
| 37 |
+
tuple: tuple,
|
| 38 |
+
set: set,
|
| 39 |
+
frozenset: frozenset,
|
| 40 |
+
deque: deque,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
sequence_types: tuple[type[Any], ...] = tuple(sequence_annotation_to_type.keys())
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Copy of Pydantic: pydantic/_internal/_utils.py with added TypeGuard
|
| 47 |
+
def lenient_issubclass(
|
| 48 |
+
cls: Any, class_or_tuple: type[_T] | tuple[type[_T], ...] | None
|
| 49 |
+
) -> TypeGuard[type[_T]]:
|
| 50 |
+
try:
|
| 51 |
+
return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
|
| 52 |
+
except TypeError: # pragma: no cover
|
| 53 |
+
if isinstance(cls, WithArgsTypes):
|
| 54 |
+
return False
|
| 55 |
+
raise # pragma: no cover
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _annotation_is_sequence(annotation: type[Any] | None) -> bool:
|
| 59 |
+
if lenient_issubclass(annotation, (str, bytes)):
|
| 60 |
+
return False
|
| 61 |
+
return lenient_issubclass(annotation, sequence_types)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def field_annotation_is_sequence(annotation: type[Any] | None) -> bool:
|
| 65 |
+
origin = get_origin(annotation)
|
| 66 |
+
if origin is Union or origin is UnionType:
|
| 67 |
+
for arg in get_args(annotation):
|
| 68 |
+
if field_annotation_is_sequence(arg):
|
| 69 |
+
return True
|
| 70 |
+
return False
|
| 71 |
+
return _annotation_is_sequence(annotation) or _annotation_is_sequence(
|
| 72 |
+
get_origin(annotation)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def value_is_sequence(value: Any) -> bool:
|
| 77 |
+
return isinstance(value, sequence_types) and not isinstance(value, (str, bytes))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _annotation_is_complex(annotation: type[Any] | None) -> bool:
|
| 81 |
+
return (
|
| 82 |
+
lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile))
|
| 83 |
+
or _annotation_is_sequence(annotation)
|
| 84 |
+
or is_dataclass(annotation)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def field_annotation_is_complex(annotation: type[Any] | None) -> bool:
|
| 89 |
+
origin = get_origin(annotation)
|
| 90 |
+
if origin is Union or origin is UnionType:
|
| 91 |
+
return any(field_annotation_is_complex(arg) for arg in get_args(annotation))
|
| 92 |
+
|
| 93 |
+
if origin is Annotated:
|
| 94 |
+
return field_annotation_is_complex(get_args(annotation)[0])
|
| 95 |
+
|
| 96 |
+
return (
|
| 97 |
+
_annotation_is_complex(annotation)
|
| 98 |
+
or _annotation_is_complex(origin)
|
| 99 |
+
or hasattr(origin, "__pydantic_core_schema__")
|
| 100 |
+
or hasattr(origin, "__get_pydantic_core_schema__")
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def field_annotation_is_scalar(annotation: Any) -> bool:
|
| 105 |
+
# handle Ellipsis here to make tuple[int, ...] work nicely
|
| 106 |
+
return annotation is Ellipsis or not field_annotation_is_complex(annotation)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool:
|
| 110 |
+
origin = get_origin(annotation)
|
| 111 |
+
if origin is Union or origin is UnionType:
|
| 112 |
+
at_least_one_scalar_sequence = False
|
| 113 |
+
for arg in get_args(annotation):
|
| 114 |
+
if field_annotation_is_scalar_sequence(arg):
|
| 115 |
+
at_least_one_scalar_sequence = True
|
| 116 |
+
continue
|
| 117 |
+
elif not field_annotation_is_scalar(arg):
|
| 118 |
+
return False
|
| 119 |
+
return at_least_one_scalar_sequence
|
| 120 |
+
return field_annotation_is_sequence(annotation) and all(
|
| 121 |
+
field_annotation_is_scalar(sub_annotation)
|
| 122 |
+
for sub_annotation in get_args(annotation)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool:
|
| 127 |
+
if lenient_issubclass(annotation, bytes):
|
| 128 |
+
return True
|
| 129 |
+
origin = get_origin(annotation)
|
| 130 |
+
if origin is Union or origin is UnionType:
|
| 131 |
+
for arg in get_args(annotation):
|
| 132 |
+
if lenient_issubclass(arg, bytes):
|
| 133 |
+
return True
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool:
|
| 138 |
+
if lenient_issubclass(annotation, UploadFile):
|
| 139 |
+
return True
|
| 140 |
+
origin = get_origin(annotation)
|
| 141 |
+
if origin is Union or origin is UnionType:
|
| 142 |
+
for arg in get_args(annotation):
|
| 143 |
+
if lenient_issubclass(arg, UploadFile):
|
| 144 |
+
return True
|
| 145 |
+
return False
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def is_bytes_sequence_annotation(annotation: Any) -> bool:
|
| 149 |
+
origin = get_origin(annotation)
|
| 150 |
+
if origin is Union or origin is UnionType:
|
| 151 |
+
at_least_one = False
|
| 152 |
+
for arg in get_args(annotation):
|
| 153 |
+
if is_bytes_sequence_annotation(arg):
|
| 154 |
+
at_least_one = True
|
| 155 |
+
continue
|
| 156 |
+
return at_least_one
|
| 157 |
+
return field_annotation_is_sequence(annotation) and all(
|
| 158 |
+
is_bytes_or_nonable_bytes_annotation(sub_annotation)
|
| 159 |
+
for sub_annotation in get_args(annotation)
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
|
| 164 |
+
origin = get_origin(annotation)
|
| 165 |
+
if origin is Union or origin is UnionType:
|
| 166 |
+
at_least_one = False
|
| 167 |
+
for arg in get_args(annotation):
|
| 168 |
+
if is_uploadfile_sequence_annotation(arg):
|
| 169 |
+
at_least_one = True
|
| 170 |
+
continue
|
| 171 |
+
return at_least_one
|
| 172 |
+
return field_annotation_is_sequence(annotation) and all(
|
| 173 |
+
is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation)
|
| 174 |
+
for sub_annotation in get_args(annotation)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def is_pydantic_v1_model_instance(obj: Any) -> bool:
|
| 179 |
+
# TODO: remove this function once the required version of Pydantic fully
|
| 180 |
+
# removes pydantic.v1
|
| 181 |
+
try:
|
| 182 |
+
with warnings.catch_warnings():
|
| 183 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 184 |
+
from pydantic import v1
|
| 185 |
+
except ImportError: # pragma: no cover
|
| 186 |
+
return False
|
| 187 |
+
return isinstance(obj, v1.BaseModel)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def is_pydantic_v1_model_class(cls: Any) -> bool:
|
| 191 |
+
# TODO: remove this function once the required version of Pydantic fully
|
| 192 |
+
# removes pydantic.v1
|
| 193 |
+
try:
|
| 194 |
+
with warnings.catch_warnings():
|
| 195 |
+
warnings.simplefilter("ignore", UserWarning)
|
| 196 |
+
from pydantic import v1
|
| 197 |
+
except ImportError: # pragma: no cover
|
| 198 |
+
return False
|
| 199 |
+
return lenient_issubclass(cls, v1.BaseModel)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def annotation_is_pydantic_v1(annotation: Any) -> bool:
|
| 203 |
+
if is_pydantic_v1_model_class(annotation):
|
| 204 |
+
return True
|
| 205 |
+
origin = get_origin(annotation)
|
| 206 |
+
if origin is Union or origin is UnionType:
|
| 207 |
+
for arg in get_args(annotation):
|
| 208 |
+
if is_pydantic_v1_model_class(arg):
|
| 209 |
+
return True
|
| 210 |
+
if field_annotation_is_sequence(annotation):
|
| 211 |
+
for sub_annotation in get_args(annotation):
|
| 212 |
+
if annotation_is_pydantic_v1(sub_annotation):
|
| 213 |
+
return True
|
| 214 |
+
return False
|
lib/python3.11/site-packages/fastapi/_compat/v2.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import warnings
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from copy import copy
|
| 5 |
+
from dataclasses import dataclass, is_dataclass
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from functools import lru_cache
|
| 8 |
+
from typing import (
|
| 9 |
+
Annotated,
|
| 10 |
+
Any,
|
| 11 |
+
Literal,
|
| 12 |
+
Union,
|
| 13 |
+
cast,
|
| 14 |
+
get_args,
|
| 15 |
+
get_origin,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from fastapi._compat import lenient_issubclass, shared
|
| 19 |
+
from fastapi.openapi.constants import REF_TEMPLATE
|
| 20 |
+
from fastapi.types import IncEx, ModelNameMap, UnionType
|
| 21 |
+
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model
|
| 22 |
+
from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError
|
| 23 |
+
from pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation
|
| 24 |
+
from pydantic import ValidationError as ValidationError
|
| 25 |
+
from pydantic._internal import _typing_extra as _pydantic_typing_extra
|
| 26 |
+
from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]
|
| 27 |
+
GetJsonSchemaHandler as GetJsonSchemaHandler,
|
| 28 |
+
)
|
| 29 |
+
from pydantic.fields import FieldInfo as FieldInfo
|
| 30 |
+
from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema
|
| 31 |
+
from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue
|
| 32 |
+
from pydantic_core import CoreSchema as CoreSchema
|
| 33 |
+
from pydantic_core import PydanticUndefined
|
| 34 |
+
from pydantic_core import Url as Url
|
| 35 |
+
from pydantic_core.core_schema import (
|
| 36 |
+
with_info_plain_validator_function as with_info_plain_validator_function,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
RequiredParam = PydanticUndefined
|
| 40 |
+
Undefined = PydanticUndefined
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_forwardref(
|
| 44 |
+
value: Any,
|
| 45 |
+
globalns: dict[str, Any] | None = None,
|
| 46 |
+
localns: dict[str, Any] | None = None,
|
| 47 |
+
) -> Any:
|
| 48 |
+
# eval_type_lenient has been deprecated since Pydantic v2.10.0b1 (PR #10530)
|
| 49 |
+
try_eval_type = getattr(_pydantic_typing_extra, "try_eval_type", None)
|
| 50 |
+
if try_eval_type is not None:
|
| 51 |
+
return try_eval_type(value, globalns, localns)[0]
|
| 52 |
+
return _pydantic_typing_extra.eval_type_lenient( # ty: ignore[deprecated]
|
| 53 |
+
value, globalns, localns
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class GenerateJsonSchema(_GenerateJsonSchema):
|
| 58 |
+
# TODO: remove when this is merged (or equivalent): https://github.com/pydantic/pydantic/pull/12841
|
| 59 |
+
# and dropping support for any version of Pydantic before that one (so, in a very long time)
|
| 60 |
+
def bytes_schema(self, schema: CoreSchema) -> JsonSchemaValue:
|
| 61 |
+
json_schema = {"type": "string", "contentMediaType": "application/octet-stream"}
|
| 62 |
+
bytes_mode = (
|
| 63 |
+
self._config.ser_json_bytes
|
| 64 |
+
if self.mode == "serialization"
|
| 65 |
+
else self._config.val_json_bytes
|
| 66 |
+
)
|
| 67 |
+
if bytes_mode == "base64":
|
| 68 |
+
json_schema["contentEncoding"] = "base64"
|
| 69 |
+
self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
|
| 70 |
+
return json_schema
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# TODO: remove when dropping support for Pydantic < v2.12.3
|
| 74 |
+
_Attrs = {
|
| 75 |
+
"default": ...,
|
| 76 |
+
"default_factory": None,
|
| 77 |
+
"alias": None,
|
| 78 |
+
"alias_priority": None,
|
| 79 |
+
"validation_alias": None,
|
| 80 |
+
"serialization_alias": None,
|
| 81 |
+
"title": None,
|
| 82 |
+
"field_title_generator": None,
|
| 83 |
+
"description": None,
|
| 84 |
+
"examples": None,
|
| 85 |
+
"exclude": None,
|
| 86 |
+
"exclude_if": None,
|
| 87 |
+
"discriminator": None,
|
| 88 |
+
"deprecated": None,
|
| 89 |
+
"json_schema_extra": None,
|
| 90 |
+
"frozen": None,
|
| 91 |
+
"validate_default": None,
|
| 92 |
+
"repr": True,
|
| 93 |
+
"init": None,
|
| 94 |
+
"init_var": None,
|
| 95 |
+
"kw_only": None,
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# TODO: remove when dropping support for Pydantic < v2.12.3
|
| 100 |
+
def asdict(field_info: FieldInfo) -> dict[str, Any]:
|
| 101 |
+
attributes = {}
|
| 102 |
+
for attr in _Attrs:
|
| 103 |
+
value = getattr(field_info, attr, Undefined)
|
| 104 |
+
if value is not Undefined:
|
| 105 |
+
attributes[attr] = value
|
| 106 |
+
return {
|
| 107 |
+
"annotation": field_info.annotation,
|
| 108 |
+
"metadata": field_info.metadata,
|
| 109 |
+
"attributes": attributes,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@dataclass
|
| 114 |
+
class ModelField:
|
| 115 |
+
field_info: FieldInfo
|
| 116 |
+
name: str
|
| 117 |
+
mode: Literal["validation", "serialization"] = "validation"
|
| 118 |
+
config: ConfigDict | None = None
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def alias(self) -> str:
|
| 122 |
+
a = self.field_info.alias
|
| 123 |
+
return a if a is not None else self.name
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def validation_alias(self) -> str | None:
|
| 127 |
+
va = self.field_info.validation_alias
|
| 128 |
+
if isinstance(va, str) and va:
|
| 129 |
+
return va
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def serialization_alias(self) -> str | None:
|
| 134 |
+
sa = self.field_info.serialization_alias
|
| 135 |
+
return sa or None
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def default(self) -> Any:
|
| 139 |
+
return self.get_default()
|
| 140 |
+
|
| 141 |
+
def __post_init__(self) -> None:
|
| 142 |
+
with warnings.catch_warnings():
|
| 143 |
+
# Pydantic >= 2.12.0 warns about field specific metadata that is unused
|
| 144 |
+
# (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we
|
| 145 |
+
# end up building the type adapter from a model field annotation so we
|
| 146 |
+
# need to ignore the warning:
|
| 147 |
+
if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12):
|
| 148 |
+
from pydantic.warnings import UnsupportedFieldAttributeWarning
|
| 149 |
+
|
| 150 |
+
warnings.simplefilter(
|
| 151 |
+
"ignore", category=UnsupportedFieldAttributeWarning
|
| 152 |
+
)
|
| 153 |
+
# TODO: remove after setting the min Pydantic to v2.12.3
|
| 154 |
+
# that adds asdict(), and use self.field_info.asdict() instead
|
| 155 |
+
field_dict = asdict(self.field_info)
|
| 156 |
+
annotated_args = (
|
| 157 |
+
field_dict["annotation"],
|
| 158 |
+
*field_dict["metadata"],
|
| 159 |
+
# this FieldInfo needs to be created again so that it doesn't include
|
| 160 |
+
# the old field info metadata and only the rest of the attributes
|
| 161 |
+
Field(**field_dict["attributes"]),
|
| 162 |
+
)
|
| 163 |
+
self._type_adapter: TypeAdapter[Any] = TypeAdapter(
|
| 164 |
+
Annotated[annotated_args], # ty: ignore[invalid-type-form]
|
| 165 |
+
config=self.config,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def get_default(self) -> Any:
|
| 169 |
+
if self.field_info.is_required():
|
| 170 |
+
return Undefined
|
| 171 |
+
return self.field_info.get_default(call_default_factory=True)
|
| 172 |
+
|
| 173 |
+
def validate(
|
| 174 |
+
self,
|
| 175 |
+
value: Any,
|
| 176 |
+
values: dict[str, Any] = {}, # noqa: B006
|
| 177 |
+
*,
|
| 178 |
+
loc: tuple[int | str, ...] = (),
|
| 179 |
+
) -> tuple[Any, list[dict[str, Any]]]:
|
| 180 |
+
try:
|
| 181 |
+
return (
|
| 182 |
+
self._type_adapter.validate_python(value, from_attributes=True),
|
| 183 |
+
[],
|
| 184 |
+
)
|
| 185 |
+
except ValidationError as exc:
|
| 186 |
+
return None, _regenerate_error_with_loc(
|
| 187 |
+
errors=exc.errors(include_url=False), loc_prefix=loc
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def serialize(
|
| 191 |
+
self,
|
| 192 |
+
value: Any,
|
| 193 |
+
*,
|
| 194 |
+
mode: Literal["json", "python"] = "json",
|
| 195 |
+
include: IncEx | None = None,
|
| 196 |
+
exclude: IncEx | None = None,
|
| 197 |
+
by_alias: bool = True,
|
| 198 |
+
exclude_unset: bool = False,
|
| 199 |
+
exclude_defaults: bool = False,
|
| 200 |
+
exclude_none: bool = False,
|
| 201 |
+
) -> Any:
|
| 202 |
+
# What calls this code passes a value that already called
|
| 203 |
+
# self._type_adapter.validate_python(value)
|
| 204 |
+
return self._type_adapter.dump_python(
|
| 205 |
+
value,
|
| 206 |
+
mode=mode,
|
| 207 |
+
include=include,
|
| 208 |
+
exclude=exclude,
|
| 209 |
+
by_alias=by_alias,
|
| 210 |
+
exclude_unset=exclude_unset,
|
| 211 |
+
exclude_defaults=exclude_defaults,
|
| 212 |
+
exclude_none=exclude_none,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
def serialize_json(
|
| 216 |
+
self,
|
| 217 |
+
value: Any,
|
| 218 |
+
*,
|
| 219 |
+
include: IncEx | None = None,
|
| 220 |
+
exclude: IncEx | None = None,
|
| 221 |
+
by_alias: bool = True,
|
| 222 |
+
exclude_unset: bool = False,
|
| 223 |
+
exclude_defaults: bool = False,
|
| 224 |
+
exclude_none: bool = False,
|
| 225 |
+
) -> bytes:
|
| 226 |
+
# What calls this code passes a value that already called
|
| 227 |
+
# self._type_adapter.validate_python(value)
|
| 228 |
+
# This uses Pydantic's dump_json() which serializes directly to JSON
|
| 229 |
+
# bytes in one pass (via Rust), avoiding the intermediate Python dict
|
| 230 |
+
# step of dump_python(mode="json") + json.dumps().
|
| 231 |
+
return self._type_adapter.dump_json(
|
| 232 |
+
value,
|
| 233 |
+
include=include,
|
| 234 |
+
exclude=exclude,
|
| 235 |
+
by_alias=by_alias,
|
| 236 |
+
exclude_unset=exclude_unset,
|
| 237 |
+
exclude_defaults=exclude_defaults,
|
| 238 |
+
exclude_none=exclude_none,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
def __hash__(self) -> int:
|
| 242 |
+
# Each ModelField is unique for our purposes, to allow making a dict from
|
| 243 |
+
# ModelField to its JSON Schema.
|
| 244 |
+
return id(self)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _has_computed_fields(field: ModelField) -> bool:
|
| 248 |
+
computed_fields = field._type_adapter.core_schema.get("schema", {}).get(
|
| 249 |
+
"computed_fields", []
|
| 250 |
+
)
|
| 251 |
+
return len(computed_fields) > 0
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def get_schema_from_model_field(
|
| 255 |
+
*,
|
| 256 |
+
field: ModelField,
|
| 257 |
+
model_name_map: ModelNameMap,
|
| 258 |
+
field_mapping: dict[
|
| 259 |
+
tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
|
| 260 |
+
],
|
| 261 |
+
separate_input_output_schemas: bool = True,
|
| 262 |
+
) -> dict[str, Any]:
|
| 263 |
+
override_mode: Literal["validation"] | None = (
|
| 264 |
+
None
|
| 265 |
+
if (separate_input_output_schemas or _has_computed_fields(field))
|
| 266 |
+
else "validation"
|
| 267 |
+
)
|
| 268 |
+
field_alias = (
|
| 269 |
+
(field.validation_alias or field.alias)
|
| 270 |
+
if field.mode == "validation"
|
| 271 |
+
else (field.serialization_alias or field.alias)
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# This expects that GenerateJsonSchema was already used to generate the definitions
|
| 275 |
+
json_schema = field_mapping[(field, override_mode or field.mode)]
|
| 276 |
+
if "$ref" not in json_schema:
|
| 277 |
+
# TODO remove when deprecating Pydantic v1
|
| 278 |
+
# Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207
|
| 279 |
+
json_schema["title"] = field.field_info.title or field_alias.title().replace(
|
| 280 |
+
"_", " "
|
| 281 |
+
)
|
| 282 |
+
return json_schema
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def get_definitions(
|
| 286 |
+
*,
|
| 287 |
+
fields: Sequence[ModelField],
|
| 288 |
+
model_name_map: ModelNameMap,
|
| 289 |
+
separate_input_output_schemas: bool = True,
|
| 290 |
+
) -> tuple[
|
| 291 |
+
dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue],
|
| 292 |
+
dict[str, dict[str, Any]],
|
| 293 |
+
]:
|
| 294 |
+
schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE)
|
| 295 |
+
validation_fields = [field for field in fields if field.mode == "validation"]
|
| 296 |
+
serialization_fields = [field for field in fields if field.mode == "serialization"]
|
| 297 |
+
flat_validation_models = get_flat_models_from_fields(
|
| 298 |
+
validation_fields, known_models=set()
|
| 299 |
+
)
|
| 300 |
+
flat_serialization_models = get_flat_models_from_fields(
|
| 301 |
+
serialization_fields, known_models=set()
|
| 302 |
+
)
|
| 303 |
+
flat_validation_model_fields = [
|
| 304 |
+
ModelField(
|
| 305 |
+
field_info=FieldInfo(annotation=model),
|
| 306 |
+
name=model.__name__,
|
| 307 |
+
mode="validation",
|
| 308 |
+
)
|
| 309 |
+
for model in flat_validation_models
|
| 310 |
+
]
|
| 311 |
+
flat_serialization_model_fields = [
|
| 312 |
+
ModelField(
|
| 313 |
+
field_info=FieldInfo(annotation=model),
|
| 314 |
+
name=model.__name__,
|
| 315 |
+
mode="serialization",
|
| 316 |
+
)
|
| 317 |
+
for model in flat_serialization_models
|
| 318 |
+
]
|
| 319 |
+
flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields
|
| 320 |
+
input_types = {f.field_info.annotation for f in fields}
|
| 321 |
+
unique_flat_model_fields = {
|
| 322 |
+
f for f in flat_model_fields if f.field_info.annotation not in input_types
|
| 323 |
+
}
|
| 324 |
+
inputs = [
|
| 325 |
+
(
|
| 326 |
+
field,
|
| 327 |
+
(
|
| 328 |
+
field.mode
|
| 329 |
+
if (separate_input_output_schemas or _has_computed_fields(field))
|
| 330 |
+
else "validation"
|
| 331 |
+
),
|
| 332 |
+
field._type_adapter.core_schema,
|
| 333 |
+
)
|
| 334 |
+
for field in list(fields) + list(unique_flat_model_fields)
|
| 335 |
+
]
|
| 336 |
+
field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs)
|
| 337 |
+
for item_def in cast(dict[str, dict[str, Any]], definitions).values():
|
| 338 |
+
if "description" in item_def:
|
| 339 |
+
item_description = cast(str, item_def["description"]).split("\f")[0]
|
| 340 |
+
item_def["description"] = item_description
|
| 341 |
+
# definitions: dict[DefsRef, dict[str, Any]]
|
| 342 |
+
# but mypy complains about general str in other places that are not declared as
|
| 343 |
+
# DefsRef, although DefsRef is just str:
|
| 344 |
+
# DefsRef = NewType('DefsRef', str)
|
| 345 |
+
# So, a cast to simplify the types here
|
| 346 |
+
return field_mapping, cast(dict[str, dict[str, Any]], definitions)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def is_scalar_field(field: ModelField) -> bool:
|
| 350 |
+
from fastapi import params
|
| 351 |
+
|
| 352 |
+
return shared.field_annotation_is_scalar(
|
| 353 |
+
field.field_info.annotation
|
| 354 |
+
) and not isinstance(field.field_info, params.Body)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
|
| 358 |
+
cls = type(field_info)
|
| 359 |
+
merged_field_info = cls.from_annotation(annotation)
|
| 360 |
+
new_field_info = copy(field_info)
|
| 361 |
+
new_field_info.metadata = merged_field_info.metadata
|
| 362 |
+
new_field_info.annotation = merged_field_info.annotation
|
| 363 |
+
return new_field_info
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
|
| 367 |
+
origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation
|
| 368 |
+
if origin_type is Union or origin_type is UnionType: # Handle optional sequences
|
| 369 |
+
union_args = get_args(field.field_info.annotation)
|
| 370 |
+
for union_arg in union_args:
|
| 371 |
+
if union_arg is type(None):
|
| 372 |
+
continue
|
| 373 |
+
origin_type = get_origin(union_arg) or union_arg
|
| 374 |
+
break
|
| 375 |
+
assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
|
| 376 |
+
return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] # ty: ignore[invalid-return-type]
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]:
|
| 380 |
+
error = ValidationError.from_exception_data(
|
| 381 |
+
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
|
| 382 |
+
).errors(include_url=False)[0]
|
| 383 |
+
error["input"] = None
|
| 384 |
+
return error # type: ignore[return-value] # ty: ignore[invalid-return-type]
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def create_body_model(
|
| 388 |
+
*, fields: Sequence[ModelField], model_name: str
|
| 389 |
+
) -> type[BaseModel]:
|
| 390 |
+
field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields}
|
| 391 |
+
BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] # ty: ignore[no-matching-overload]
|
| 392 |
+
return BodyModel
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def get_model_fields(model: type[BaseModel]) -> list[ModelField]:
|
| 396 |
+
model_fields: list[ModelField] = []
|
| 397 |
+
for name, field_info in model.model_fields.items():
|
| 398 |
+
type_ = field_info.annotation
|
| 399 |
+
if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_):
|
| 400 |
+
model_config = None
|
| 401 |
+
else:
|
| 402 |
+
model_config = model.model_config
|
| 403 |
+
model_fields.append(
|
| 404 |
+
ModelField(
|
| 405 |
+
field_info=field_info,
|
| 406 |
+
name=name,
|
| 407 |
+
config=model_config,
|
| 408 |
+
)
|
| 409 |
+
)
|
| 410 |
+
return model_fields
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@lru_cache
|
| 414 |
+
def get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]:
|
| 415 |
+
return get_model_fields(model)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
# Duplicate of several schema functions from Pydantic v1 to make them compatible with
|
| 419 |
+
# Pydantic v2 and allow mixing the models
|
| 420 |
+
|
| 421 |
+
TypeModelOrEnum = type["BaseModel"] | type[Enum]
|
| 422 |
+
TypeModelSet = set[TypeModelOrEnum]
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def normalize_name(name: str) -> str:
|
| 426 |
+
return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]:
|
| 430 |
+
name_model_map = {}
|
| 431 |
+
for model in unique_models:
|
| 432 |
+
model_name = normalize_name(model.__name__)
|
| 433 |
+
name_model_map[model_name] = model
|
| 434 |
+
return {v: k for k, v in name_model_map.items()}
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def get_flat_models_from_model(
|
| 438 |
+
model: type["BaseModel"], known_models: TypeModelSet | None = None
|
| 439 |
+
) -> TypeModelSet:
|
| 440 |
+
known_models = known_models or set()
|
| 441 |
+
fields = get_model_fields(model)
|
| 442 |
+
get_flat_models_from_fields(fields, known_models=known_models)
|
| 443 |
+
return known_models
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def get_flat_models_from_annotation(
|
| 447 |
+
annotation: Any, known_models: TypeModelSet
|
| 448 |
+
) -> TypeModelSet:
|
| 449 |
+
origin = get_origin(annotation)
|
| 450 |
+
if origin is not None:
|
| 451 |
+
for arg in get_args(annotation):
|
| 452 |
+
if lenient_issubclass(arg, (BaseModel, Enum)):
|
| 453 |
+
if arg not in known_models:
|
| 454 |
+
known_models.add(arg) # type: ignore[arg-type]
|
| 455 |
+
if lenient_issubclass(arg, BaseModel):
|
| 456 |
+
get_flat_models_from_model(arg, known_models=known_models)
|
| 457 |
+
else:
|
| 458 |
+
get_flat_models_from_annotation(arg, known_models=known_models)
|
| 459 |
+
return known_models
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def get_flat_models_from_field(
|
| 463 |
+
field: ModelField, known_models: TypeModelSet
|
| 464 |
+
) -> TypeModelSet:
|
| 465 |
+
field_type = field.field_info.annotation
|
| 466 |
+
if lenient_issubclass(field_type, BaseModel):
|
| 467 |
+
if field_type in known_models:
|
| 468 |
+
return known_models
|
| 469 |
+
known_models.add(field_type)
|
| 470 |
+
get_flat_models_from_model(field_type, known_models=known_models)
|
| 471 |
+
elif lenient_issubclass(field_type, Enum):
|
| 472 |
+
known_models.add(field_type)
|
| 473 |
+
else:
|
| 474 |
+
get_flat_models_from_annotation(field_type, known_models=known_models)
|
| 475 |
+
return known_models
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def get_flat_models_from_fields(
|
| 479 |
+
fields: Sequence[ModelField], known_models: TypeModelSet
|
| 480 |
+
) -> TypeModelSet:
|
| 481 |
+
for field in fields:
|
| 482 |
+
get_flat_models_from_field(field, known_models=known_models)
|
| 483 |
+
return known_models
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _regenerate_error_with_loc(
|
| 487 |
+
*, errors: Sequence[Any], loc_prefix: tuple[str | int, ...]
|
| 488 |
+
) -> list[dict[str, Any]]:
|
| 489 |
+
updated_loc_errors: list[Any] = [
|
| 490 |
+
{**err, "loc": loc_prefix + err.get("loc", ())} for err in errors
|
| 491 |
+
]
|
| 492 |
+
|
| 493 |
+
return updated_loc_errors
|
lib/python3.11/site-packages/fastapi/applications.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.11/site-packages/fastapi/background.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Annotated, Any
|
| 3 |
+
|
| 4 |
+
from annotated_doc import Doc
|
| 5 |
+
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
|
| 6 |
+
from typing_extensions import ParamSpec
|
| 7 |
+
|
| 8 |
+
P = ParamSpec("P")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BackgroundTasks(StarletteBackgroundTasks):
|
| 12 |
+
"""
|
| 13 |
+
A collection of background tasks that will be called after a response has been
|
| 14 |
+
sent to the client.
|
| 15 |
+
|
| 16 |
+
Read more about it in the
|
| 17 |
+
[FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| 18 |
+
|
| 19 |
+
## Example
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
from fastapi import BackgroundTasks, FastAPI
|
| 23 |
+
|
| 24 |
+
app = FastAPI()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def write_notification(email: str, message=""):
|
| 28 |
+
with open("log.txt", mode="w") as email_file:
|
| 29 |
+
content = f"notification for {email}: {message}"
|
| 30 |
+
email_file.write(content)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@app.post("/send-notification/{email}")
|
| 34 |
+
async def send_notification(email: str, background_tasks: BackgroundTasks):
|
| 35 |
+
background_tasks.add_task(write_notification, email, message="some notification")
|
| 36 |
+
return {"message": "Notification sent in the background"}
|
| 37 |
+
```
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def add_task(
|
| 41 |
+
self,
|
| 42 |
+
func: Annotated[
|
| 43 |
+
Callable[P, Any],
|
| 44 |
+
Doc(
|
| 45 |
+
"""
|
| 46 |
+
The function to call after the response is sent.
|
| 47 |
+
|
| 48 |
+
It can be a regular `def` function or an `async def` function.
|
| 49 |
+
"""
|
| 50 |
+
),
|
| 51 |
+
],
|
| 52 |
+
*args: P.args,
|
| 53 |
+
**kwargs: P.kwargs,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Add a function to be called in the background after the response is sent.
|
| 57 |
+
|
| 58 |
+
Read more about it in the
|
| 59 |
+
[FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| 60 |
+
"""
|
| 61 |
+
return super().add_task(func, *args, **kwargs)
|
lib/python3.11/site-packages/fastapi/cli.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from fastapi_cli.cli import main as cli_main
|
| 3 |
+
|
| 4 |
+
except ImportError: # pragma: no cover
|
| 5 |
+
cli_main = None # type: ignore
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main() -> None:
|
| 9 |
+
if not cli_main: # type: ignore[truthy-function]
|
| 10 |
+
message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n'
|
| 11 |
+
print(message)
|
| 12 |
+
raise RuntimeError(message) # noqa: B904
|
| 13 |
+
cli_main()
|
lib/python3.11/site-packages/fastapi/concurrency.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import AsyncGenerator
|
| 2 |
+
from contextlib import AbstractContextManager
|
| 3 |
+
from contextlib import asynccontextmanager as asynccontextmanager
|
| 4 |
+
from typing import TypeVar
|
| 5 |
+
|
| 6 |
+
import anyio.to_thread
|
| 7 |
+
from anyio import CapacityLimiter
|
| 8 |
+
from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa
|
| 9 |
+
from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa
|
| 10 |
+
from starlette.concurrency import ( # noqa
|
| 11 |
+
run_until_first_complete as run_until_first_complete,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
_T = TypeVar("_T")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@asynccontextmanager
|
| 18 |
+
async def contextmanager_in_threadpool(
|
| 19 |
+
cm: AbstractContextManager[_T],
|
| 20 |
+
) -> AsyncGenerator[_T, None]:
|
| 21 |
+
# blocking __exit__ from running waiting on a free thread
|
| 22 |
+
# can create race conditions/deadlocks if the context manager itself
|
| 23 |
+
# has its own internal pool (e.g. a database connection pool)
|
| 24 |
+
# to avoid this we let __exit__ run without a capacity limit
|
| 25 |
+
# since we're creating a new limiter for each call, any non-zero limit
|
| 26 |
+
# works (1 is arbitrary)
|
| 27 |
+
exit_limiter = CapacityLimiter(1)
|
| 28 |
+
try:
|
| 29 |
+
yield await run_in_threadpool(cm.__enter__)
|
| 30 |
+
except Exception as e:
|
| 31 |
+
ok = bool(
|
| 32 |
+
await anyio.to_thread.run_sync(
|
| 33 |
+
cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter
|
| 34 |
+
)
|
| 35 |
+
)
|
| 36 |
+
if not ok:
|
| 37 |
+
raise e
|
| 38 |
+
else:
|
| 39 |
+
await anyio.to_thread.run_sync(
|
| 40 |
+
cm.__exit__, None, None, None, limiter=exit_limiter
|
| 41 |
+
)
|
lib/python3.11/site-packages/fastapi/datastructures.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Mapping
|
| 2 |
+
from typing import (
|
| 3 |
+
Annotated,
|
| 4 |
+
Any,
|
| 5 |
+
BinaryIO,
|
| 6 |
+
TypeVar,
|
| 7 |
+
cast,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
from annotated_doc import Doc
|
| 11 |
+
from pydantic import GetJsonSchemaHandler
|
| 12 |
+
from starlette.datastructures import URL as URL # noqa: F401
|
| 13 |
+
from starlette.datastructures import Address as Address # noqa: F401
|
| 14 |
+
from starlette.datastructures import FormData as FormData # noqa: F401
|
| 15 |
+
from starlette.datastructures import Headers as Headers # noqa: F401
|
| 16 |
+
from starlette.datastructures import QueryParams as QueryParams # noqa: F401
|
| 17 |
+
from starlette.datastructures import State as State # noqa: F401
|
| 18 |
+
from starlette.datastructures import UploadFile as StarletteUploadFile
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class UploadFile(StarletteUploadFile):
|
| 22 |
+
"""
|
| 23 |
+
A file uploaded in a request.
|
| 24 |
+
|
| 25 |
+
Define it as a *path operation function* (or dependency) parameter.
|
| 26 |
+
|
| 27 |
+
If you are using a regular `def` function, you can use the `upload_file.file`
|
| 28 |
+
attribute to access the raw standard Python file (blocking, not async), useful and
|
| 29 |
+
needed for non-async code.
|
| 30 |
+
|
| 31 |
+
Read more about it in the
|
| 32 |
+
[FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/).
|
| 33 |
+
|
| 34 |
+
## Example
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
from typing import Annotated
|
| 38 |
+
|
| 39 |
+
from fastapi import FastAPI, File, UploadFile
|
| 40 |
+
|
| 41 |
+
app = FastAPI()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@app.post("/files/")
|
| 45 |
+
async def create_file(file: Annotated[bytes, File()]):
|
| 46 |
+
return {"file_size": len(file)}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@app.post("/uploadfile/")
|
| 50 |
+
async def create_upload_file(file: UploadFile):
|
| 51 |
+
return {"filename": file.filename}
|
| 52 |
+
```
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
file: Annotated[
|
| 56 |
+
BinaryIO,
|
| 57 |
+
Doc("The standard Python file object (non-async)."),
|
| 58 |
+
]
|
| 59 |
+
filename: Annotated[str | None, Doc("The original file name.")]
|
| 60 |
+
size: Annotated[int | None, Doc("The size of the file in bytes.")]
|
| 61 |
+
headers: Annotated[Headers, Doc("The headers of the request.")]
|
| 62 |
+
content_type: Annotated[
|
| 63 |
+
str | None, Doc("The content type of the request, from the headers.")
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
async def write(
|
| 67 |
+
self,
|
| 68 |
+
data: Annotated[
|
| 69 |
+
bytes,
|
| 70 |
+
Doc(
|
| 71 |
+
"""
|
| 72 |
+
The bytes to write to the file.
|
| 73 |
+
"""
|
| 74 |
+
),
|
| 75 |
+
],
|
| 76 |
+
) -> None:
|
| 77 |
+
"""
|
| 78 |
+
Write some bytes to the file.
|
| 79 |
+
|
| 80 |
+
You normally wouldn't use this from a file you read in a request.
|
| 81 |
+
|
| 82 |
+
To be awaitable, compatible with async, this is run in threadpool.
|
| 83 |
+
"""
|
| 84 |
+
return await super().write(data)
|
| 85 |
+
|
| 86 |
+
async def read(
|
| 87 |
+
self,
|
| 88 |
+
size: Annotated[
|
| 89 |
+
int,
|
| 90 |
+
Doc(
|
| 91 |
+
"""
|
| 92 |
+
The number of bytes to read from the file.
|
| 93 |
+
"""
|
| 94 |
+
),
|
| 95 |
+
] = -1,
|
| 96 |
+
) -> bytes:
|
| 97 |
+
"""
|
| 98 |
+
Read some bytes from the file.
|
| 99 |
+
|
| 100 |
+
To be awaitable, compatible with async, this is run in threadpool.
|
| 101 |
+
"""
|
| 102 |
+
return await super().read(size)
|
| 103 |
+
|
| 104 |
+
async def seek(
|
| 105 |
+
self,
|
| 106 |
+
offset: Annotated[
|
| 107 |
+
int,
|
| 108 |
+
Doc(
|
| 109 |
+
"""
|
| 110 |
+
The position in bytes to seek to in the file.
|
| 111 |
+
"""
|
| 112 |
+
),
|
| 113 |
+
],
|
| 114 |
+
) -> None:
|
| 115 |
+
"""
|
| 116 |
+
Move to a position in the file.
|
| 117 |
+
|
| 118 |
+
Any next read or write will be done from that position.
|
| 119 |
+
|
| 120 |
+
To be awaitable, compatible with async, this is run in threadpool.
|
| 121 |
+
"""
|
| 122 |
+
return await super().seek(offset)
|
| 123 |
+
|
| 124 |
+
async def close(self) -> None:
|
| 125 |
+
"""
|
| 126 |
+
Close the file.
|
| 127 |
+
|
| 128 |
+
To be awaitable, compatible with async, this is run in threadpool.
|
| 129 |
+
"""
|
| 130 |
+
return await super().close()
|
| 131 |
+
|
| 132 |
+
@classmethod
|
| 133 |
+
def _validate(cls, __input_value: Any, _: Any) -> "UploadFile":
|
| 134 |
+
if not isinstance(__input_value, StarletteUploadFile):
|
| 135 |
+
raise ValueError(f"Expected UploadFile, received: {type(__input_value)}")
|
| 136 |
+
return cast(UploadFile, __input_value)
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def __get_pydantic_json_schema__(
|
| 140 |
+
cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler
|
| 141 |
+
) -> dict[str, Any]:
|
| 142 |
+
return {"type": "string", "contentMediaType": "application/octet-stream"}
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def __get_pydantic_core_schema__(
|
| 146 |
+
cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]
|
| 147 |
+
) -> Mapping[str, Any]:
|
| 148 |
+
from ._compat.v2 import with_info_plain_validator_function
|
| 149 |
+
|
| 150 |
+
return with_info_plain_validator_function(cls._validate)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class DefaultPlaceholder:
|
| 154 |
+
"""
|
| 155 |
+
You shouldn't use this class directly.
|
| 156 |
+
|
| 157 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 158 |
+
if the overridden default value was truthy.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(self, value: Any):
|
| 162 |
+
self.value = value
|
| 163 |
+
|
| 164 |
+
def __bool__(self) -> bool:
|
| 165 |
+
return bool(self.value)
|
| 166 |
+
|
| 167 |
+
def __eq__(self, o: object) -> bool:
|
| 168 |
+
return isinstance(o, DefaultPlaceholder) and o.value == self.value
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
DefaultType = TypeVar("DefaultType")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def Default(value: DefaultType) -> DefaultType:
|
| 175 |
+
"""
|
| 176 |
+
You shouldn't use this function directly.
|
| 177 |
+
|
| 178 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 179 |
+
if the overridden default value was truthy.
|
| 180 |
+
"""
|
| 181 |
+
return DefaultPlaceholder(value) # type: ignore
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Sentinel for "parameter not provided" in Param/FieldInfo.
|
| 185 |
+
# Typed as None to satisfy ty
|
| 186 |
+
_Unset = Default(None)
|
lib/python3.11/site-packages/fastapi/dependencies/__init__.py
ADDED
|
File without changes
|
lib/python3.11/site-packages/fastapi/dependencies/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (205 Bytes). View file
|
|
|
lib/python3.11/site-packages/fastapi/dependencies/__pycache__/models.cpython-311.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/dependencies/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (44.4 kB). View file
|
|
|
lib/python3.11/site-packages/fastapi/dependencies/models.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import sys
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from functools import cached_property, partial
|
| 6 |
+
from typing import Any, Literal
|
| 7 |
+
|
| 8 |
+
from fastapi._compat import ModelField
|
| 9 |
+
from fastapi.security.base import SecurityBase
|
| 10 |
+
from fastapi.types import DependencyCacheKey
|
| 11 |
+
|
| 12 |
+
if sys.version_info >= (3, 13): # pragma: no cover
|
| 13 |
+
from inspect import iscoroutinefunction
|
| 14 |
+
else: # pragma: no cover
|
| 15 |
+
from asyncio import iscoroutinefunction
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _unwrapped_call(call: Callable[..., Any] | None) -> Any:
|
| 19 |
+
if call is None:
|
| 20 |
+
return call # pragma: no cover
|
| 21 |
+
unwrapped = inspect.unwrap(_impartial(call))
|
| 22 |
+
return unwrapped
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _impartial(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 26 |
+
while isinstance(func, partial):
|
| 27 |
+
func = func.func
|
| 28 |
+
return func
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class Dependant:
|
| 33 |
+
path_params: list[ModelField] = field(default_factory=list)
|
| 34 |
+
query_params: list[ModelField] = field(default_factory=list)
|
| 35 |
+
header_params: list[ModelField] = field(default_factory=list)
|
| 36 |
+
cookie_params: list[ModelField] = field(default_factory=list)
|
| 37 |
+
body_params: list[ModelField] = field(default_factory=list)
|
| 38 |
+
dependencies: list["Dependant"] = field(default_factory=list)
|
| 39 |
+
name: str | None = None
|
| 40 |
+
call: Callable[..., Any] | None = None
|
| 41 |
+
request_param_name: str | None = None
|
| 42 |
+
websocket_param_name: str | None = None
|
| 43 |
+
http_connection_param_name: str | None = None
|
| 44 |
+
response_param_name: str | None = None
|
| 45 |
+
background_tasks_param_name: str | None = None
|
| 46 |
+
security_scopes_param_name: str | None = None
|
| 47 |
+
own_oauth_scopes: list[str] | None = None
|
| 48 |
+
parent_oauth_scopes: list[str] | None = None
|
| 49 |
+
use_cache: bool = True
|
| 50 |
+
path: str | None = None
|
| 51 |
+
scope: Literal["function", "request"] | None = None
|
| 52 |
+
|
| 53 |
+
@cached_property
|
| 54 |
+
def oauth_scopes(self) -> list[str]:
|
| 55 |
+
scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else []
|
| 56 |
+
# This doesn't use a set to preserve order, just in case
|
| 57 |
+
for scope in self.own_oauth_scopes or []:
|
| 58 |
+
if scope not in scopes:
|
| 59 |
+
scopes.append(scope)
|
| 60 |
+
return scopes
|
| 61 |
+
|
| 62 |
+
@cached_property
|
| 63 |
+
def cache_key(self) -> DependencyCacheKey:
|
| 64 |
+
scopes_for_cache = (
|
| 65 |
+
tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else ()
|
| 66 |
+
)
|
| 67 |
+
return (
|
| 68 |
+
self.call,
|
| 69 |
+
scopes_for_cache,
|
| 70 |
+
self.computed_scope or "",
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
@cached_property
|
| 74 |
+
def _uses_scopes(self) -> bool:
|
| 75 |
+
if self.own_oauth_scopes:
|
| 76 |
+
return True
|
| 77 |
+
if self.security_scopes_param_name is not None:
|
| 78 |
+
return True
|
| 79 |
+
if self._is_security_scheme:
|
| 80 |
+
return True
|
| 81 |
+
for sub_dep in self.dependencies:
|
| 82 |
+
if sub_dep._uses_scopes:
|
| 83 |
+
return True
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
@cached_property
|
| 87 |
+
def _is_security_scheme(self) -> bool:
|
| 88 |
+
if self.call is None:
|
| 89 |
+
return False # pragma: no cover
|
| 90 |
+
unwrapped = _unwrapped_call(self.call)
|
| 91 |
+
return isinstance(unwrapped, SecurityBase)
|
| 92 |
+
|
| 93 |
+
# Mainly to get the type of SecurityBase, but it's the same self.call
|
| 94 |
+
@cached_property
|
| 95 |
+
def _security_scheme(self) -> SecurityBase:
|
| 96 |
+
unwrapped = _unwrapped_call(self.call)
|
| 97 |
+
assert isinstance(unwrapped, SecurityBase)
|
| 98 |
+
return unwrapped
|
| 99 |
+
|
| 100 |
+
@cached_property
|
| 101 |
+
def _security_dependencies(self) -> list["Dependant"]:
|
| 102 |
+
security_deps = [dep for dep in self.dependencies if dep._is_security_scheme]
|
| 103 |
+
return security_deps
|
| 104 |
+
|
| 105 |
+
@cached_property
|
| 106 |
+
def is_gen_callable(self) -> bool:
|
| 107 |
+
if self.call is None:
|
| 108 |
+
return False # pragma: no cover
|
| 109 |
+
if inspect.isgeneratorfunction(
|
| 110 |
+
_impartial(self.call)
|
| 111 |
+
) or inspect.isgeneratorfunction(_unwrapped_call(self.call)):
|
| 112 |
+
return True
|
| 113 |
+
if inspect.isclass(_unwrapped_call(self.call)):
|
| 114 |
+
return False
|
| 115 |
+
dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004
|
| 116 |
+
if dunder_call is None:
|
| 117 |
+
return False # pragma: no cover
|
| 118 |
+
if inspect.isgeneratorfunction(
|
| 119 |
+
_impartial(dunder_call)
|
| 120 |
+
) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)):
|
| 121 |
+
return True
|
| 122 |
+
dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004
|
| 123 |
+
if dunder_unwrapped_call is None:
|
| 124 |
+
return False # pragma: no cover
|
| 125 |
+
if inspect.isgeneratorfunction(
|
| 126 |
+
_impartial(dunder_unwrapped_call)
|
| 127 |
+
) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)):
|
| 128 |
+
return True
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
@cached_property
|
| 132 |
+
def is_async_gen_callable(self) -> bool:
|
| 133 |
+
if self.call is None:
|
| 134 |
+
return False # pragma: no cover
|
| 135 |
+
if inspect.isasyncgenfunction(
|
| 136 |
+
_impartial(self.call)
|
| 137 |
+
) or inspect.isasyncgenfunction(_unwrapped_call(self.call)):
|
| 138 |
+
return True
|
| 139 |
+
if inspect.isclass(_unwrapped_call(self.call)):
|
| 140 |
+
return False
|
| 141 |
+
dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004
|
| 142 |
+
if dunder_call is None:
|
| 143 |
+
return False # pragma: no cover
|
| 144 |
+
if inspect.isasyncgenfunction(
|
| 145 |
+
_impartial(dunder_call)
|
| 146 |
+
) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)):
|
| 147 |
+
return True
|
| 148 |
+
dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004
|
| 149 |
+
if dunder_unwrapped_call is None:
|
| 150 |
+
return False # pragma: no cover
|
| 151 |
+
if inspect.isasyncgenfunction(
|
| 152 |
+
_impartial(dunder_unwrapped_call)
|
| 153 |
+
) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)):
|
| 154 |
+
return True
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
@cached_property
|
| 158 |
+
def is_coroutine_callable(self) -> bool:
|
| 159 |
+
if self.call is None:
|
| 160 |
+
return False # pragma: no cover
|
| 161 |
+
if inspect.isroutine(_impartial(self.call)) and iscoroutinefunction(
|
| 162 |
+
_impartial(self.call)
|
| 163 |
+
):
|
| 164 |
+
return True
|
| 165 |
+
if inspect.isroutine(_unwrapped_call(self.call)) and iscoroutinefunction(
|
| 166 |
+
_unwrapped_call(self.call)
|
| 167 |
+
):
|
| 168 |
+
return True
|
| 169 |
+
if inspect.isclass(_unwrapped_call(self.call)):
|
| 170 |
+
return False
|
| 171 |
+
dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004
|
| 172 |
+
if dunder_call is None:
|
| 173 |
+
return False # pragma: no cover
|
| 174 |
+
if iscoroutinefunction(_impartial(dunder_call)) or iscoroutinefunction(
|
| 175 |
+
_unwrapped_call(dunder_call)
|
| 176 |
+
):
|
| 177 |
+
return True
|
| 178 |
+
dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004
|
| 179 |
+
if dunder_unwrapped_call is None:
|
| 180 |
+
return False # pragma: no cover
|
| 181 |
+
if iscoroutinefunction(
|
| 182 |
+
_impartial(dunder_unwrapped_call)
|
| 183 |
+
) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)):
|
| 184 |
+
return True
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
@cached_property
|
| 188 |
+
def computed_scope(self) -> str | None:
|
| 189 |
+
if self.scope:
|
| 190 |
+
return self.scope
|
| 191 |
+
if self.is_gen_callable or self.is_async_gen_callable:
|
| 192 |
+
return "request"
|
| 193 |
+
return None
|
lib/python3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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import inspect
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import (
|
| 5 |
+
AsyncGenerator,
|
| 6 |
+
AsyncIterable,
|
| 7 |
+
AsyncIterator,
|
| 8 |
+
Callable,
|
| 9 |
+
Generator,
|
| 10 |
+
Iterable,
|
| 11 |
+
Iterator,
|
| 12 |
+
Mapping,
|
| 13 |
+
Sequence,
|
| 14 |
+
)
|
| 15 |
+
from contextlib import AsyncExitStack, contextmanager
|
| 16 |
+
from copy import copy, deepcopy
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import (
|
| 19 |
+
Annotated,
|
| 20 |
+
Any,
|
| 21 |
+
ForwardRef,
|
| 22 |
+
Literal,
|
| 23 |
+
Union,
|
| 24 |
+
cast,
|
| 25 |
+
get_args,
|
| 26 |
+
get_origin,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from fastapi import params
|
| 30 |
+
from fastapi._compat import (
|
| 31 |
+
ModelField,
|
| 32 |
+
RequiredParam,
|
| 33 |
+
Undefined,
|
| 34 |
+
copy_field_info,
|
| 35 |
+
create_body_model,
|
| 36 |
+
evaluate_forwardref,
|
| 37 |
+
field_annotation_is_scalar,
|
| 38 |
+
field_annotation_is_scalar_sequence,
|
| 39 |
+
field_annotation_is_sequence,
|
| 40 |
+
get_cached_model_fields,
|
| 41 |
+
get_missing_field_error,
|
| 42 |
+
is_bytes_or_nonable_bytes_annotation,
|
| 43 |
+
is_bytes_sequence_annotation,
|
| 44 |
+
is_scalar_field,
|
| 45 |
+
is_uploadfile_or_nonable_uploadfile_annotation,
|
| 46 |
+
is_uploadfile_sequence_annotation,
|
| 47 |
+
lenient_issubclass,
|
| 48 |
+
sequence_types,
|
| 49 |
+
serialize_sequence_value,
|
| 50 |
+
value_is_sequence,
|
| 51 |
+
)
|
| 52 |
+
from fastapi.background import BackgroundTasks
|
| 53 |
+
from fastapi.concurrency import (
|
| 54 |
+
asynccontextmanager,
|
| 55 |
+
contextmanager_in_threadpool,
|
| 56 |
+
)
|
| 57 |
+
from fastapi.dependencies.models import Dependant
|
| 58 |
+
from fastapi.exceptions import DependencyScopeError
|
| 59 |
+
from fastapi.logger import logger
|
| 60 |
+
from fastapi.security.oauth2 import SecurityScopes
|
| 61 |
+
from fastapi.types import DependencyCacheKey
|
| 62 |
+
from fastapi.utils import create_model_field, get_path_param_names
|
| 63 |
+
from pydantic import BaseModel, Json
|
| 64 |
+
from pydantic.fields import FieldInfo
|
| 65 |
+
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
|
| 66 |
+
from starlette.concurrency import run_in_threadpool
|
| 67 |
+
from starlette.datastructures import (
|
| 68 |
+
FormData,
|
| 69 |
+
Headers,
|
| 70 |
+
ImmutableMultiDict,
|
| 71 |
+
QueryParams,
|
| 72 |
+
UploadFile,
|
| 73 |
+
)
|
| 74 |
+
from starlette.requests import HTTPConnection, Request
|
| 75 |
+
from starlette.responses import Response
|
| 76 |
+
from starlette.websockets import WebSocket
|
| 77 |
+
from typing_inspection.typing_objects import is_typealiastype
|
| 78 |
+
|
| 79 |
+
multipart_not_installed_error = (
|
| 80 |
+
'Form data requires "python-multipart" to be installed. \n'
|
| 81 |
+
'You can install "python-multipart" with: \n\n'
|
| 82 |
+
"pip install python-multipart\n"
|
| 83 |
+
)
|
| 84 |
+
multipart_incorrect_install_error = (
|
| 85 |
+
'Form data requires "python-multipart" to be installed. '
|
| 86 |
+
'It seems you installed "multipart" instead. \n'
|
| 87 |
+
'You can remove "multipart" with: \n\n'
|
| 88 |
+
"pip uninstall multipart\n\n"
|
| 89 |
+
'And then install "python-multipart" with: \n\n'
|
| 90 |
+
"pip install python-multipart\n"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def ensure_multipart_is_installed() -> None:
|
| 95 |
+
try:
|
| 96 |
+
from python_multipart import __version__
|
| 97 |
+
|
| 98 |
+
# Import an attribute that can be mocked/deleted in testing
|
| 99 |
+
assert __version__ > "0.0.12"
|
| 100 |
+
except (ImportError, AssertionError):
|
| 101 |
+
try:
|
| 102 |
+
# __version__ is available in both multiparts, and can be mocked
|
| 103 |
+
from multipart import ( # type: ignore[no-redef,import-untyped]
|
| 104 |
+
__version__,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
assert __version__
|
| 108 |
+
try:
|
| 109 |
+
# parse_options_header is only available in the right multipart
|
| 110 |
+
from multipart.multipart import ( # type: ignore[import-untyped]
|
| 111 |
+
parse_options_header,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
assert parse_options_header
|
| 115 |
+
except ImportError:
|
| 116 |
+
logger.error(multipart_incorrect_install_error)
|
| 117 |
+
raise RuntimeError(multipart_incorrect_install_error) from None
|
| 118 |
+
except ImportError:
|
| 119 |
+
logger.error(multipart_not_installed_error)
|
| 120 |
+
raise RuntimeError(multipart_not_installed_error) from None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant:
|
| 124 |
+
assert callable(depends.dependency), (
|
| 125 |
+
"A parameter-less dependency must have a callable dependency"
|
| 126 |
+
)
|
| 127 |
+
own_oauth_scopes: list[str] = []
|
| 128 |
+
if isinstance(depends, params.Security) and depends.scopes:
|
| 129 |
+
own_oauth_scopes.extend(depends.scopes)
|
| 130 |
+
return get_dependant(
|
| 131 |
+
path=path,
|
| 132 |
+
call=depends.dependency,
|
| 133 |
+
scope=depends.scope,
|
| 134 |
+
own_oauth_scopes=own_oauth_scopes,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_flat_dependant(
|
| 139 |
+
dependant: Dependant,
|
| 140 |
+
*,
|
| 141 |
+
skip_repeats: bool = False,
|
| 142 |
+
visited: list[DependencyCacheKey] | None = None,
|
| 143 |
+
parent_oauth_scopes: list[str] | None = None,
|
| 144 |
+
) -> Dependant:
|
| 145 |
+
if visited is None:
|
| 146 |
+
visited = []
|
| 147 |
+
visited.append(dependant.cache_key)
|
| 148 |
+
use_parent_oauth_scopes = (parent_oauth_scopes or []) + (
|
| 149 |
+
dependant.oauth_scopes or []
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
flat_dependant = Dependant(
|
| 153 |
+
path_params=dependant.path_params.copy(),
|
| 154 |
+
query_params=dependant.query_params.copy(),
|
| 155 |
+
header_params=dependant.header_params.copy(),
|
| 156 |
+
cookie_params=dependant.cookie_params.copy(),
|
| 157 |
+
body_params=dependant.body_params.copy(),
|
| 158 |
+
name=dependant.name,
|
| 159 |
+
call=dependant.call,
|
| 160 |
+
request_param_name=dependant.request_param_name,
|
| 161 |
+
websocket_param_name=dependant.websocket_param_name,
|
| 162 |
+
http_connection_param_name=dependant.http_connection_param_name,
|
| 163 |
+
response_param_name=dependant.response_param_name,
|
| 164 |
+
background_tasks_param_name=dependant.background_tasks_param_name,
|
| 165 |
+
security_scopes_param_name=dependant.security_scopes_param_name,
|
| 166 |
+
own_oauth_scopes=dependant.own_oauth_scopes,
|
| 167 |
+
parent_oauth_scopes=use_parent_oauth_scopes,
|
| 168 |
+
use_cache=dependant.use_cache,
|
| 169 |
+
path=dependant.path,
|
| 170 |
+
scope=dependant.scope,
|
| 171 |
+
)
|
| 172 |
+
for sub_dependant in dependant.dependencies:
|
| 173 |
+
if skip_repeats and sub_dependant.cache_key in visited:
|
| 174 |
+
continue
|
| 175 |
+
flat_sub = get_flat_dependant(
|
| 176 |
+
sub_dependant,
|
| 177 |
+
skip_repeats=skip_repeats,
|
| 178 |
+
visited=visited,
|
| 179 |
+
parent_oauth_scopes=flat_dependant.oauth_scopes,
|
| 180 |
+
)
|
| 181 |
+
flat_dependant.dependencies.append(flat_sub)
|
| 182 |
+
flat_dependant.path_params.extend(flat_sub.path_params)
|
| 183 |
+
flat_dependant.query_params.extend(flat_sub.query_params)
|
| 184 |
+
flat_dependant.header_params.extend(flat_sub.header_params)
|
| 185 |
+
flat_dependant.cookie_params.extend(flat_sub.cookie_params)
|
| 186 |
+
flat_dependant.body_params.extend(flat_sub.body_params)
|
| 187 |
+
flat_dependant.dependencies.extend(flat_sub.dependencies)
|
| 188 |
+
|
| 189 |
+
return flat_dependant
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]:
|
| 193 |
+
if not fields:
|
| 194 |
+
return fields
|
| 195 |
+
first_field = fields[0]
|
| 196 |
+
if len(fields) == 1 and lenient_issubclass(
|
| 197 |
+
first_field.field_info.annotation, BaseModel
|
| 198 |
+
):
|
| 199 |
+
fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)
|
| 200 |
+
return fields_to_extract
|
| 201 |
+
return fields
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def get_flat_params(dependant: Dependant) -> list[ModelField]:
|
| 205 |
+
flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
|
| 206 |
+
path_params = _get_flat_fields_from_params(flat_dependant.path_params)
|
| 207 |
+
query_params = _get_flat_fields_from_params(flat_dependant.query_params)
|
| 208 |
+
header_params = _get_flat_fields_from_params(flat_dependant.header_params)
|
| 209 |
+
cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)
|
| 210 |
+
return path_params + query_params + header_params + cookie_params
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _get_signature(call: Callable[..., Any]) -> inspect.Signature:
|
| 214 |
+
try:
|
| 215 |
+
signature = inspect.signature(call, eval_str=True)
|
| 216 |
+
except NameError:
|
| 217 |
+
# Handle type annotations with if TYPE_CHECKING, not used by FastAPI
|
| 218 |
+
# e.g. dependency return types
|
| 219 |
+
if sys.version_info >= (3, 14):
|
| 220 |
+
from annotationlib import Format
|
| 221 |
+
|
| 222 |
+
signature = inspect.signature(call, annotation_format=Format.FORWARDREF)
|
| 223 |
+
else:
|
| 224 |
+
signature = inspect.signature(call)
|
| 225 |
+
return signature
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
|
| 229 |
+
signature = _get_signature(call)
|
| 230 |
+
unwrapped = inspect.unwrap(call)
|
| 231 |
+
globalns = getattr(unwrapped, "__globals__", {})
|
| 232 |
+
typed_params = [
|
| 233 |
+
inspect.Parameter(
|
| 234 |
+
name=param.name,
|
| 235 |
+
kind=param.kind,
|
| 236 |
+
default=param.default,
|
| 237 |
+
annotation=get_typed_annotation(param.annotation, globalns),
|
| 238 |
+
)
|
| 239 |
+
for param in signature.parameters.values()
|
| 240 |
+
]
|
| 241 |
+
typed_signature = inspect.Signature(typed_params)
|
| 242 |
+
return typed_signature
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any:
|
| 246 |
+
if isinstance(annotation, str):
|
| 247 |
+
annotation = ForwardRef(annotation)
|
| 248 |
+
annotation = evaluate_forwardref(annotation, globalns, globalns)
|
| 249 |
+
if annotation is type(None):
|
| 250 |
+
return None
|
| 251 |
+
return annotation
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def get_typed_return_annotation(call: Callable[..., Any]) -> Any:
|
| 255 |
+
signature = _get_signature(call)
|
| 256 |
+
unwrapped = inspect.unwrap(call)
|
| 257 |
+
annotation = signature.return_annotation
|
| 258 |
+
|
| 259 |
+
if annotation is inspect.Signature.empty:
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
globalns = getattr(unwrapped, "__globals__", {})
|
| 263 |
+
return get_typed_annotation(annotation, globalns)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
_STREAM_ORIGINS = {
|
| 267 |
+
AsyncIterable,
|
| 268 |
+
AsyncIterator,
|
| 269 |
+
AsyncGenerator,
|
| 270 |
+
Iterable,
|
| 271 |
+
Iterator,
|
| 272 |
+
Generator,
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def get_stream_item_type(annotation: Any) -> Any | None:
|
| 277 |
+
origin = get_origin(annotation)
|
| 278 |
+
if origin is not None and origin in _STREAM_ORIGINS:
|
| 279 |
+
type_args = get_args(annotation)
|
| 280 |
+
if type_args:
|
| 281 |
+
return type_args[0]
|
| 282 |
+
return Any
|
| 283 |
+
return None
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def get_dependant(
|
| 287 |
+
*,
|
| 288 |
+
path: str,
|
| 289 |
+
call: Callable[..., Any],
|
| 290 |
+
name: str | None = None,
|
| 291 |
+
own_oauth_scopes: list[str] | None = None,
|
| 292 |
+
parent_oauth_scopes: list[str] | None = None,
|
| 293 |
+
use_cache: bool = True,
|
| 294 |
+
scope: Literal["function", "request"] | None = None,
|
| 295 |
+
) -> Dependant:
|
| 296 |
+
dependant = Dependant(
|
| 297 |
+
call=call,
|
| 298 |
+
name=name,
|
| 299 |
+
path=path,
|
| 300 |
+
use_cache=use_cache,
|
| 301 |
+
scope=scope,
|
| 302 |
+
own_oauth_scopes=own_oauth_scopes,
|
| 303 |
+
parent_oauth_scopes=parent_oauth_scopes,
|
| 304 |
+
)
|
| 305 |
+
current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or [])
|
| 306 |
+
path_param_names = get_path_param_names(path)
|
| 307 |
+
endpoint_signature = get_typed_signature(call)
|
| 308 |
+
signature_params = endpoint_signature.parameters
|
| 309 |
+
for param_name, param in signature_params.items():
|
| 310 |
+
is_path_param = param_name in path_param_names
|
| 311 |
+
param_details = analyze_param(
|
| 312 |
+
param_name=param_name,
|
| 313 |
+
annotation=param.annotation,
|
| 314 |
+
value=param.default,
|
| 315 |
+
is_path_param=is_path_param,
|
| 316 |
+
)
|
| 317 |
+
if param_details.depends is not None:
|
| 318 |
+
assert param_details.depends.dependency
|
| 319 |
+
if (
|
| 320 |
+
(dependant.is_gen_callable or dependant.is_async_gen_callable)
|
| 321 |
+
and dependant.computed_scope == "request"
|
| 322 |
+
and param_details.depends.scope == "function"
|
| 323 |
+
):
|
| 324 |
+
assert dependant.call
|
| 325 |
+
call_name = getattr(dependant.call, "__name__", "<unnamed_callable>")
|
| 326 |
+
raise DependencyScopeError(
|
| 327 |
+
f'The dependency "{call_name}" has a scope of '
|
| 328 |
+
'"request", it cannot depend on dependencies with scope "function".'
|
| 329 |
+
)
|
| 330 |
+
sub_own_oauth_scopes: list[str] = []
|
| 331 |
+
if isinstance(param_details.depends, params.Security):
|
| 332 |
+
if param_details.depends.scopes:
|
| 333 |
+
sub_own_oauth_scopes = list(param_details.depends.scopes)
|
| 334 |
+
sub_dependant = get_dependant(
|
| 335 |
+
path=path,
|
| 336 |
+
call=param_details.depends.dependency,
|
| 337 |
+
name=param_name,
|
| 338 |
+
own_oauth_scopes=sub_own_oauth_scopes,
|
| 339 |
+
parent_oauth_scopes=current_scopes,
|
| 340 |
+
use_cache=param_details.depends.use_cache,
|
| 341 |
+
scope=param_details.depends.scope,
|
| 342 |
+
)
|
| 343 |
+
dependant.dependencies.append(sub_dependant)
|
| 344 |
+
continue
|
| 345 |
+
if add_non_field_param_to_dependency(
|
| 346 |
+
param_name=param_name,
|
| 347 |
+
type_annotation=param_details.type_annotation,
|
| 348 |
+
dependant=dependant,
|
| 349 |
+
):
|
| 350 |
+
assert param_details.field is None, (
|
| 351 |
+
f"Cannot specify multiple FastAPI annotations for {param_name!r}"
|
| 352 |
+
)
|
| 353 |
+
continue
|
| 354 |
+
assert param_details.field is not None
|
| 355 |
+
if isinstance(param_details.field.field_info, params.Body):
|
| 356 |
+
dependant.body_params.append(param_details.field)
|
| 357 |
+
else:
|
| 358 |
+
add_param_to_fields(field=param_details.field, dependant=dependant)
|
| 359 |
+
return dependant
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def add_non_field_param_to_dependency(
|
| 363 |
+
*, param_name: str, type_annotation: Any, dependant: Dependant
|
| 364 |
+
) -> bool | None:
|
| 365 |
+
if lenient_issubclass(type_annotation, Request):
|
| 366 |
+
dependant.request_param_name = param_name
|
| 367 |
+
return True
|
| 368 |
+
elif lenient_issubclass(type_annotation, WebSocket):
|
| 369 |
+
dependant.websocket_param_name = param_name
|
| 370 |
+
return True
|
| 371 |
+
elif lenient_issubclass(type_annotation, HTTPConnection):
|
| 372 |
+
dependant.http_connection_param_name = param_name
|
| 373 |
+
return True
|
| 374 |
+
elif lenient_issubclass(type_annotation, Response):
|
| 375 |
+
dependant.response_param_name = param_name
|
| 376 |
+
return True
|
| 377 |
+
elif lenient_issubclass(type_annotation, StarletteBackgroundTasks):
|
| 378 |
+
dependant.background_tasks_param_name = param_name
|
| 379 |
+
return True
|
| 380 |
+
elif lenient_issubclass(type_annotation, SecurityScopes):
|
| 381 |
+
dependant.security_scopes_param_name = param_name
|
| 382 |
+
return True
|
| 383 |
+
return None
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@dataclass
|
| 387 |
+
class ParamDetails:
|
| 388 |
+
type_annotation: Any
|
| 389 |
+
depends: params.Depends | None
|
| 390 |
+
field: ModelField | None
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def analyze_param(
|
| 394 |
+
*,
|
| 395 |
+
param_name: str,
|
| 396 |
+
annotation: Any,
|
| 397 |
+
value: Any,
|
| 398 |
+
is_path_param: bool,
|
| 399 |
+
) -> ParamDetails:
|
| 400 |
+
field_info = None
|
| 401 |
+
depends = None
|
| 402 |
+
type_annotation: Any = Any
|
| 403 |
+
use_annotation: Any = Any
|
| 404 |
+
if is_typealiastype(annotation):
|
| 405 |
+
# unpack in case PEP 695 type syntax is used
|
| 406 |
+
annotation = annotation.__value__
|
| 407 |
+
if annotation is not inspect.Signature.empty:
|
| 408 |
+
use_annotation = annotation
|
| 409 |
+
type_annotation = annotation
|
| 410 |
+
# Extract Annotated info
|
| 411 |
+
if get_origin(use_annotation) is Annotated:
|
| 412 |
+
annotated_args = get_args(annotation)
|
| 413 |
+
type_annotation = annotated_args[0]
|
| 414 |
+
fastapi_annotations = [
|
| 415 |
+
arg
|
| 416 |
+
for arg in annotated_args[1:]
|
| 417 |
+
if isinstance(arg, (FieldInfo, params.Depends))
|
| 418 |
+
]
|
| 419 |
+
fastapi_specific_annotations = [
|
| 420 |
+
arg
|
| 421 |
+
for arg in fastapi_annotations
|
| 422 |
+
if isinstance(
|
| 423 |
+
arg,
|
| 424 |
+
(
|
| 425 |
+
params.Param,
|
| 426 |
+
params.Body,
|
| 427 |
+
params.Depends,
|
| 428 |
+
),
|
| 429 |
+
)
|
| 430 |
+
]
|
| 431 |
+
if fastapi_specific_annotations:
|
| 432 |
+
fastapi_annotation: FieldInfo | params.Depends | None = (
|
| 433 |
+
fastapi_specific_annotations[-1]
|
| 434 |
+
)
|
| 435 |
+
else:
|
| 436 |
+
fastapi_annotation = None
|
| 437 |
+
# Set default for Annotated FieldInfo
|
| 438 |
+
if isinstance(fastapi_annotation, FieldInfo):
|
| 439 |
+
# Copy `field_info` because we mutate `field_info.default` below.
|
| 440 |
+
field_info = copy_field_info(
|
| 441 |
+
field_info=fastapi_annotation,
|
| 442 |
+
annotation=use_annotation,
|
| 443 |
+
)
|
| 444 |
+
assert (
|
| 445 |
+
field_info.default == Undefined or field_info.default == RequiredParam
|
| 446 |
+
), (
|
| 447 |
+
f"`{field_info.__class__.__name__}` default value cannot be set in"
|
| 448 |
+
f" `Annotated` for {param_name!r}. Set the default value with `=` instead."
|
| 449 |
+
)
|
| 450 |
+
if value is not inspect.Signature.empty:
|
| 451 |
+
assert not is_path_param, "Path parameters cannot have default values"
|
| 452 |
+
field_info.default = value
|
| 453 |
+
else:
|
| 454 |
+
field_info.default = RequiredParam
|
| 455 |
+
# Get Annotated Depends
|
| 456 |
+
elif isinstance(fastapi_annotation, params.Depends):
|
| 457 |
+
depends = fastapi_annotation
|
| 458 |
+
# Get Depends from default value
|
| 459 |
+
if isinstance(value, params.Depends):
|
| 460 |
+
assert depends is None, (
|
| 461 |
+
"Cannot specify `Depends` in `Annotated` and default value"
|
| 462 |
+
f" together for {param_name!r}"
|
| 463 |
+
)
|
| 464 |
+
assert field_info is None, (
|
| 465 |
+
"Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a"
|
| 466 |
+
f" default value together for {param_name!r}"
|
| 467 |
+
)
|
| 468 |
+
depends = value
|
| 469 |
+
# Get FieldInfo from default value
|
| 470 |
+
elif isinstance(value, FieldInfo):
|
| 471 |
+
assert field_info is None, (
|
| 472 |
+
"Cannot specify FastAPI annotations in `Annotated` and default value"
|
| 473 |
+
f" together for {param_name!r}"
|
| 474 |
+
)
|
| 475 |
+
field_info = value
|
| 476 |
+
if isinstance(field_info, FieldInfo):
|
| 477 |
+
field_info.annotation = type_annotation
|
| 478 |
+
|
| 479 |
+
# Get Depends from type annotation
|
| 480 |
+
if depends is not None and depends.dependency is None:
|
| 481 |
+
# Copy `depends` before mutating it
|
| 482 |
+
depends = copy(depends)
|
| 483 |
+
depends = dataclasses.replace(depends, dependency=type_annotation)
|
| 484 |
+
|
| 485 |
+
# Handle non-param type annotations like Request
|
| 486 |
+
# Only apply special handling when there's no explicit Depends - if there's a Depends,
|
| 487 |
+
# the dependency will be called and its return value used instead of the special injection
|
| 488 |
+
if depends is None and lenient_issubclass(
|
| 489 |
+
type_annotation,
|
| 490 |
+
(
|
| 491 |
+
Request,
|
| 492 |
+
WebSocket,
|
| 493 |
+
HTTPConnection,
|
| 494 |
+
Response,
|
| 495 |
+
StarletteBackgroundTasks,
|
| 496 |
+
SecurityScopes,
|
| 497 |
+
),
|
| 498 |
+
):
|
| 499 |
+
assert field_info is None, (
|
| 500 |
+
f"Cannot specify FastAPI annotation for type {type_annotation!r}"
|
| 501 |
+
)
|
| 502 |
+
# Handle default assignations, neither field_info nor depends was not found in Annotated nor default value
|
| 503 |
+
elif field_info is None and depends is None:
|
| 504 |
+
default_value = value if value is not inspect.Signature.empty else RequiredParam
|
| 505 |
+
if is_path_param:
|
| 506 |
+
# We might check here that `default_value is RequiredParam`, but the fact is that the same
|
| 507 |
+
# parameter might sometimes be a path parameter and sometimes not. See
|
| 508 |
+
# `tests/test_infer_param_optionality.py` for an example.
|
| 509 |
+
field_info = params.Path(annotation=use_annotation)
|
| 510 |
+
elif is_uploadfile_or_nonable_uploadfile_annotation(
|
| 511 |
+
type_annotation
|
| 512 |
+
) or is_uploadfile_sequence_annotation(type_annotation):
|
| 513 |
+
field_info = params.File(annotation=use_annotation, default=default_value)
|
| 514 |
+
elif not field_annotation_is_scalar(annotation=type_annotation):
|
| 515 |
+
field_info = params.Body(annotation=use_annotation, default=default_value)
|
| 516 |
+
else:
|
| 517 |
+
field_info = params.Query(annotation=use_annotation, default=default_value)
|
| 518 |
+
|
| 519 |
+
field = None
|
| 520 |
+
# It's a field_info, not a dependency
|
| 521 |
+
if field_info is not None:
|
| 522 |
+
# Handle field_info.in_
|
| 523 |
+
if is_path_param:
|
| 524 |
+
assert isinstance(field_info, params.Path), (
|
| 525 |
+
f"Cannot use `{field_info.__class__.__name__}` for path param"
|
| 526 |
+
f" {param_name!r}"
|
| 527 |
+
)
|
| 528 |
+
elif (
|
| 529 |
+
isinstance(field_info, params.Param)
|
| 530 |
+
and getattr(field_info, "in_", None) is None
|
| 531 |
+
):
|
| 532 |
+
field_info.in_ = params.ParamTypes.query
|
| 533 |
+
use_annotation_from_field_info = use_annotation
|
| 534 |
+
if isinstance(field_info, params.Form):
|
| 535 |
+
ensure_multipart_is_installed()
|
| 536 |
+
if not field_info.alias and getattr(field_info, "convert_underscores", None):
|
| 537 |
+
alias = param_name.replace("_", "-")
|
| 538 |
+
else:
|
| 539 |
+
alias = field_info.alias or param_name
|
| 540 |
+
field_info.alias = alias
|
| 541 |
+
field = create_model_field(
|
| 542 |
+
name=param_name,
|
| 543 |
+
type_=use_annotation_from_field_info,
|
| 544 |
+
default=field_info.default,
|
| 545 |
+
alias=alias,
|
| 546 |
+
field_info=field_info,
|
| 547 |
+
)
|
| 548 |
+
if is_path_param:
|
| 549 |
+
assert is_scalar_field(field=field), (
|
| 550 |
+
"Path params must be of one of the supported types"
|
| 551 |
+
)
|
| 552 |
+
elif isinstance(field_info, params.Query):
|
| 553 |
+
assert (
|
| 554 |
+
is_scalar_field(field)
|
| 555 |
+
or field_annotation_is_scalar_sequence(field.field_info.annotation)
|
| 556 |
+
or lenient_issubclass(field.field_info.annotation, BaseModel)
|
| 557 |
+
), f"Query parameter {param_name!r} must be one of the supported types"
|
| 558 |
+
|
| 559 |
+
return ParamDetails(type_annotation=type_annotation, depends=depends, field=field)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
|
| 563 |
+
field_info = field.field_info
|
| 564 |
+
field_info_in = getattr(field_info, "in_", None)
|
| 565 |
+
if field_info_in == params.ParamTypes.path:
|
| 566 |
+
dependant.path_params.append(field)
|
| 567 |
+
elif field_info_in == params.ParamTypes.query:
|
| 568 |
+
dependant.query_params.append(field)
|
| 569 |
+
elif field_info_in == params.ParamTypes.header:
|
| 570 |
+
dependant.header_params.append(field)
|
| 571 |
+
else:
|
| 572 |
+
assert field_info_in == params.ParamTypes.cookie, (
|
| 573 |
+
f"non-body parameters must be in path, query, header or cookie: {field.name}"
|
| 574 |
+
)
|
| 575 |
+
dependant.cookie_params.append(field)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
async def _solve_generator(
|
| 579 |
+
*, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any]
|
| 580 |
+
) -> Any:
|
| 581 |
+
assert dependant.call
|
| 582 |
+
if dependant.is_async_gen_callable:
|
| 583 |
+
cm = asynccontextmanager(dependant.call)(**sub_values)
|
| 584 |
+
elif dependant.is_gen_callable:
|
| 585 |
+
cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values))
|
| 586 |
+
return await stack.enter_async_context(cm)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
@dataclass
|
| 590 |
+
class SolvedDependency:
|
| 591 |
+
values: dict[str, Any]
|
| 592 |
+
errors: list[Any]
|
| 593 |
+
background_tasks: StarletteBackgroundTasks | None
|
| 594 |
+
response: Response
|
| 595 |
+
dependency_cache: dict[DependencyCacheKey, Any]
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
async def solve_dependencies(
|
| 599 |
+
*,
|
| 600 |
+
request: Request | WebSocket,
|
| 601 |
+
dependant: Dependant,
|
| 602 |
+
body: dict[str, Any] | FormData | bytes | None = None,
|
| 603 |
+
background_tasks: StarletteBackgroundTasks | None = None,
|
| 604 |
+
response: Response | None = None,
|
| 605 |
+
dependency_overrides_provider: Any | None = None,
|
| 606 |
+
dependency_cache: dict[DependencyCacheKey, Any] | None = None,
|
| 607 |
+
# TODO: remove this parameter later, no longer used, not removing it yet as some
|
| 608 |
+
# people might be monkey patching this function (although that's not supported)
|
| 609 |
+
async_exit_stack: AsyncExitStack,
|
| 610 |
+
embed_body_fields: bool,
|
| 611 |
+
) -> SolvedDependency:
|
| 612 |
+
request_astack = request.scope.get("fastapi_inner_astack")
|
| 613 |
+
assert isinstance(request_astack, AsyncExitStack), (
|
| 614 |
+
"fastapi_inner_astack not found in request scope"
|
| 615 |
+
)
|
| 616 |
+
function_astack = request.scope.get("fastapi_function_astack")
|
| 617 |
+
assert isinstance(function_astack, AsyncExitStack), (
|
| 618 |
+
"fastapi_function_astack not found in request scope"
|
| 619 |
+
)
|
| 620 |
+
values: dict[str, Any] = {}
|
| 621 |
+
errors: list[Any] = []
|
| 622 |
+
if response is None:
|
| 623 |
+
response = Response()
|
| 624 |
+
del response.headers["content-length"]
|
| 625 |
+
response.status_code = None # type: ignore
|
| 626 |
+
if dependency_cache is None:
|
| 627 |
+
dependency_cache = {}
|
| 628 |
+
for sub_dependant in dependant.dependencies:
|
| 629 |
+
sub_dependant.call = cast(Callable[..., Any], sub_dependant.call)
|
| 630 |
+
call = sub_dependant.call
|
| 631 |
+
use_sub_dependant = sub_dependant
|
| 632 |
+
if (
|
| 633 |
+
dependency_overrides_provider
|
| 634 |
+
and dependency_overrides_provider.dependency_overrides
|
| 635 |
+
):
|
| 636 |
+
original_call = sub_dependant.call
|
| 637 |
+
call = getattr(
|
| 638 |
+
dependency_overrides_provider, "dependency_overrides", {}
|
| 639 |
+
).get(original_call, original_call)
|
| 640 |
+
use_path: str = sub_dependant.path # type: ignore
|
| 641 |
+
use_sub_dependant = get_dependant(
|
| 642 |
+
path=use_path,
|
| 643 |
+
call=call,
|
| 644 |
+
name=sub_dependant.name,
|
| 645 |
+
parent_oauth_scopes=sub_dependant.oauth_scopes,
|
| 646 |
+
scope=sub_dependant.scope,
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
solved_result = await solve_dependencies(
|
| 650 |
+
request=request,
|
| 651 |
+
dependant=use_sub_dependant,
|
| 652 |
+
body=body,
|
| 653 |
+
background_tasks=background_tasks,
|
| 654 |
+
response=response,
|
| 655 |
+
dependency_overrides_provider=dependency_overrides_provider,
|
| 656 |
+
dependency_cache=dependency_cache,
|
| 657 |
+
async_exit_stack=async_exit_stack,
|
| 658 |
+
embed_body_fields=embed_body_fields,
|
| 659 |
+
)
|
| 660 |
+
background_tasks = solved_result.background_tasks
|
| 661 |
+
if solved_result.errors:
|
| 662 |
+
errors.extend(solved_result.errors)
|
| 663 |
+
continue
|
| 664 |
+
if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:
|
| 665 |
+
solved = dependency_cache[sub_dependant.cache_key]
|
| 666 |
+
elif (
|
| 667 |
+
use_sub_dependant.is_gen_callable or use_sub_dependant.is_async_gen_callable
|
| 668 |
+
):
|
| 669 |
+
use_astack = request_astack
|
| 670 |
+
if sub_dependant.scope == "function":
|
| 671 |
+
use_astack = function_astack
|
| 672 |
+
solved = await _solve_generator(
|
| 673 |
+
dependant=use_sub_dependant,
|
| 674 |
+
stack=use_astack,
|
| 675 |
+
sub_values=solved_result.values,
|
| 676 |
+
)
|
| 677 |
+
elif use_sub_dependant.is_coroutine_callable:
|
| 678 |
+
solved = await call(**solved_result.values)
|
| 679 |
+
else:
|
| 680 |
+
solved = await run_in_threadpool(call, **solved_result.values)
|
| 681 |
+
if sub_dependant.name is not None:
|
| 682 |
+
values[sub_dependant.name] = solved
|
| 683 |
+
if sub_dependant.cache_key not in dependency_cache:
|
| 684 |
+
dependency_cache[sub_dependant.cache_key] = solved
|
| 685 |
+
path_values, path_errors = request_params_to_args(
|
| 686 |
+
dependant.path_params, request.path_params
|
| 687 |
+
)
|
| 688 |
+
query_values, query_errors = request_params_to_args(
|
| 689 |
+
dependant.query_params, request.query_params
|
| 690 |
+
)
|
| 691 |
+
header_values, header_errors = request_params_to_args(
|
| 692 |
+
dependant.header_params, request.headers
|
| 693 |
+
)
|
| 694 |
+
cookie_values, cookie_errors = request_params_to_args(
|
| 695 |
+
dependant.cookie_params, request.cookies
|
| 696 |
+
)
|
| 697 |
+
values.update(path_values)
|
| 698 |
+
values.update(query_values)
|
| 699 |
+
values.update(header_values)
|
| 700 |
+
values.update(cookie_values)
|
| 701 |
+
errors += path_errors + query_errors + header_errors + cookie_errors
|
| 702 |
+
if dependant.body_params:
|
| 703 |
+
(
|
| 704 |
+
body_values,
|
| 705 |
+
body_errors,
|
| 706 |
+
) = await request_body_to_args( # body_params checked above
|
| 707 |
+
body_fields=dependant.body_params,
|
| 708 |
+
received_body=body,
|
| 709 |
+
embed_body_fields=embed_body_fields,
|
| 710 |
+
)
|
| 711 |
+
values.update(body_values)
|
| 712 |
+
errors.extend(body_errors)
|
| 713 |
+
if dependant.http_connection_param_name:
|
| 714 |
+
values[dependant.http_connection_param_name] = request
|
| 715 |
+
if dependant.request_param_name and isinstance(request, Request):
|
| 716 |
+
values[dependant.request_param_name] = request
|
| 717 |
+
elif dependant.websocket_param_name and isinstance(request, WebSocket):
|
| 718 |
+
values[dependant.websocket_param_name] = request
|
| 719 |
+
if dependant.background_tasks_param_name:
|
| 720 |
+
if background_tasks is None:
|
| 721 |
+
background_tasks = BackgroundTasks()
|
| 722 |
+
values[dependant.background_tasks_param_name] = background_tasks
|
| 723 |
+
if dependant.response_param_name:
|
| 724 |
+
values[dependant.response_param_name] = response
|
| 725 |
+
if dependant.security_scopes_param_name:
|
| 726 |
+
values[dependant.security_scopes_param_name] = SecurityScopes(
|
| 727 |
+
scopes=dependant.oauth_scopes
|
| 728 |
+
)
|
| 729 |
+
return SolvedDependency(
|
| 730 |
+
values=values,
|
| 731 |
+
errors=errors,
|
| 732 |
+
background_tasks=background_tasks,
|
| 733 |
+
response=response,
|
| 734 |
+
dependency_cache=dependency_cache,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
def _validate_value_with_model_field(
|
| 739 |
+
*, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...]
|
| 740 |
+
) -> tuple[Any, list[Any]]:
|
| 741 |
+
if value is None:
|
| 742 |
+
if field.field_info.is_required():
|
| 743 |
+
return None, [get_missing_field_error(loc=loc)]
|
| 744 |
+
else:
|
| 745 |
+
return deepcopy(field.default), []
|
| 746 |
+
return field.validate(value, values, loc=loc)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _is_json_field(field: ModelField) -> bool:
|
| 750 |
+
return any(type(item) is Json for item in field.field_info.metadata)
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def _get_multidict_value(
|
| 754 |
+
field: ModelField, values: Mapping[str, Any], alias: str | None = None
|
| 755 |
+
) -> Any:
|
| 756 |
+
alias = alias or get_validation_alias(field)
|
| 757 |
+
if (
|
| 758 |
+
(not _is_json_field(field))
|
| 759 |
+
and field_annotation_is_sequence(field.field_info.annotation)
|
| 760 |
+
and isinstance(values, (ImmutableMultiDict, Headers))
|
| 761 |
+
):
|
| 762 |
+
value = values.getlist(alias)
|
| 763 |
+
else:
|
| 764 |
+
value = values.get(alias, None)
|
| 765 |
+
if (
|
| 766 |
+
value is None
|
| 767 |
+
or (
|
| 768 |
+
isinstance(field.field_info, params.Form)
|
| 769 |
+
and isinstance(value, str) # For type checks
|
| 770 |
+
and value == ""
|
| 771 |
+
)
|
| 772 |
+
or (
|
| 773 |
+
field_annotation_is_sequence(field.field_info.annotation)
|
| 774 |
+
and len(value) == 0
|
| 775 |
+
)
|
| 776 |
+
):
|
| 777 |
+
if field.field_info.is_required():
|
| 778 |
+
return
|
| 779 |
+
else:
|
| 780 |
+
return deepcopy(field.default)
|
| 781 |
+
return value
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
def request_params_to_args(
|
| 785 |
+
fields: Sequence[ModelField],
|
| 786 |
+
received_params: Mapping[str, Any] | QueryParams | Headers,
|
| 787 |
+
) -> tuple[dict[str, Any], list[Any]]:
|
| 788 |
+
values: dict[str, Any] = {}
|
| 789 |
+
errors: list[dict[str, Any]] = []
|
| 790 |
+
|
| 791 |
+
if not fields:
|
| 792 |
+
return values, errors
|
| 793 |
+
|
| 794 |
+
first_field = fields[0]
|
| 795 |
+
fields_to_extract = fields
|
| 796 |
+
single_not_embedded_field = False
|
| 797 |
+
default_convert_underscores = True
|
| 798 |
+
if len(fields) == 1 and lenient_issubclass(
|
| 799 |
+
first_field.field_info.annotation, BaseModel
|
| 800 |
+
):
|
| 801 |
+
fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)
|
| 802 |
+
single_not_embedded_field = True
|
| 803 |
+
# If headers are in a Pydantic model, the way to disable convert_underscores
|
| 804 |
+
# would be with Header(convert_underscores=False) at the Pydantic model level
|
| 805 |
+
default_convert_underscores = getattr(
|
| 806 |
+
first_field.field_info, "convert_underscores", True
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
params_to_process: dict[str, Any] = {}
|
| 810 |
+
|
| 811 |
+
processed_keys = set()
|
| 812 |
+
|
| 813 |
+
for field in fields_to_extract:
|
| 814 |
+
alias = None
|
| 815 |
+
if isinstance(received_params, Headers):
|
| 816 |
+
# Handle fields extracted from a Pydantic Model for a header, each field
|
| 817 |
+
# doesn't have a FieldInfo of type Header with the default convert_underscores=True
|
| 818 |
+
convert_underscores = getattr(
|
| 819 |
+
field.field_info, "convert_underscores", default_convert_underscores
|
| 820 |
+
)
|
| 821 |
+
if convert_underscores:
|
| 822 |
+
alias = get_validation_alias(field)
|
| 823 |
+
if alias == field.name:
|
| 824 |
+
alias = alias.replace("_", "-")
|
| 825 |
+
value = _get_multidict_value(field, received_params, alias=alias)
|
| 826 |
+
if value is not None:
|
| 827 |
+
params_to_process[get_validation_alias(field)] = value
|
| 828 |
+
processed_keys.add(alias or get_validation_alias(field))
|
| 829 |
+
# For headers with convert_underscores=True, mark both the converted
|
| 830 |
+
# header name and the original field alias as processed to avoid
|
| 831 |
+
# accepting the original alias as an extra header.
|
| 832 |
+
processed_keys.add(get_validation_alias(field))
|
| 833 |
+
|
| 834 |
+
for key in received_params.keys():
|
| 835 |
+
if key not in processed_keys:
|
| 836 |
+
if isinstance(received_params, (ImmutableMultiDict, Headers)):
|
| 837 |
+
value = received_params.getlist(key)
|
| 838 |
+
if isinstance(value, list) and (len(value) == 1):
|
| 839 |
+
params_to_process[key] = value[0]
|
| 840 |
+
else:
|
| 841 |
+
params_to_process[key] = value
|
| 842 |
+
else:
|
| 843 |
+
params_to_process[key] = received_params.get(key)
|
| 844 |
+
|
| 845 |
+
if single_not_embedded_field:
|
| 846 |
+
field_info = first_field.field_info
|
| 847 |
+
assert isinstance(field_info, params.Param), (
|
| 848 |
+
"Params must be subclasses of Param"
|
| 849 |
+
)
|
| 850 |
+
loc: tuple[str, ...] = (field_info.in_.value,)
|
| 851 |
+
v_, errors_ = _validate_value_with_model_field(
|
| 852 |
+
field=first_field, value=params_to_process, values=values, loc=loc
|
| 853 |
+
)
|
| 854 |
+
return {first_field.name: v_}, errors_
|
| 855 |
+
|
| 856 |
+
for field in fields:
|
| 857 |
+
value = _get_multidict_value(field, received_params)
|
| 858 |
+
field_info = field.field_info
|
| 859 |
+
assert isinstance(field_info, params.Param), (
|
| 860 |
+
"Params must be subclasses of Param"
|
| 861 |
+
)
|
| 862 |
+
loc = (field_info.in_.value, get_validation_alias(field))
|
| 863 |
+
v_, errors_ = _validate_value_with_model_field(
|
| 864 |
+
field=field, value=value, values=values, loc=loc
|
| 865 |
+
)
|
| 866 |
+
if errors_:
|
| 867 |
+
errors.extend(errors_)
|
| 868 |
+
else:
|
| 869 |
+
values[field.name] = v_
|
| 870 |
+
return values, errors
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def is_union_of_base_models(field_type: Any) -> bool:
|
| 874 |
+
"""Check if field type is a Union where all members are BaseModel subclasses."""
|
| 875 |
+
from fastapi.types import UnionType
|
| 876 |
+
|
| 877 |
+
origin = get_origin(field_type)
|
| 878 |
+
|
| 879 |
+
# Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+)
|
| 880 |
+
if origin is not Union and origin is not UnionType:
|
| 881 |
+
return False
|
| 882 |
+
|
| 883 |
+
union_args = get_args(field_type)
|
| 884 |
+
|
| 885 |
+
for arg in union_args:
|
| 886 |
+
if not lenient_issubclass(arg, BaseModel):
|
| 887 |
+
return False
|
| 888 |
+
|
| 889 |
+
return True
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def _should_embed_body_fields(fields: list[ModelField]) -> bool:
|
| 893 |
+
if not fields:
|
| 894 |
+
return False
|
| 895 |
+
# More than one dependency could have the same field, it would show up as multiple
|
| 896 |
+
# fields but it's the same one, so count them by name
|
| 897 |
+
body_param_names_set = {field.name for field in fields}
|
| 898 |
+
# A top level field has to be a single field, not multiple
|
| 899 |
+
if len(body_param_names_set) > 1:
|
| 900 |
+
return True
|
| 901 |
+
first_field = fields[0]
|
| 902 |
+
# If it explicitly specifies it is embedded, it has to be embedded
|
| 903 |
+
if getattr(first_field.field_info, "embed", None):
|
| 904 |
+
return True
|
| 905 |
+
# If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level
|
| 906 |
+
# otherwise it has to be embedded, so that the key value pair can be extracted
|
| 907 |
+
if (
|
| 908 |
+
isinstance(first_field.field_info, params.Form)
|
| 909 |
+
and not lenient_issubclass(first_field.field_info.annotation, BaseModel)
|
| 910 |
+
and not is_union_of_base_models(first_field.field_info.annotation)
|
| 911 |
+
):
|
| 912 |
+
return True
|
| 913 |
+
return False
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
async def _extract_form_body(
|
| 917 |
+
body_fields: list[ModelField],
|
| 918 |
+
received_body: FormData,
|
| 919 |
+
) -> dict[str, Any]:
|
| 920 |
+
values = {}
|
| 921 |
+
|
| 922 |
+
for field in body_fields:
|
| 923 |
+
value = _get_multidict_value(field, received_body)
|
| 924 |
+
field_info = field.field_info
|
| 925 |
+
if (
|
| 926 |
+
isinstance(field_info, params.File)
|
| 927 |
+
and is_bytes_or_nonable_bytes_annotation(field.field_info.annotation)
|
| 928 |
+
and isinstance(value, UploadFile)
|
| 929 |
+
):
|
| 930 |
+
value = await value.read()
|
| 931 |
+
elif (
|
| 932 |
+
is_bytes_sequence_annotation(field.field_info.annotation)
|
| 933 |
+
and isinstance(field_info, params.File)
|
| 934 |
+
and value_is_sequence(value)
|
| 935 |
+
):
|
| 936 |
+
# For types
|
| 937 |
+
assert isinstance(value, sequence_types)
|
| 938 |
+
results: list[bytes | str] = []
|
| 939 |
+
for sub_value in value:
|
| 940 |
+
results.append(await sub_value.read())
|
| 941 |
+
value = serialize_sequence_value(field=field, value=results)
|
| 942 |
+
if value is not None:
|
| 943 |
+
values[get_validation_alias(field)] = value
|
| 944 |
+
field_aliases = {get_validation_alias(field) for field in body_fields}
|
| 945 |
+
for key in received_body.keys():
|
| 946 |
+
if key not in field_aliases:
|
| 947 |
+
param_values = received_body.getlist(key)
|
| 948 |
+
if len(param_values) == 1:
|
| 949 |
+
values[key] = param_values[0]
|
| 950 |
+
else:
|
| 951 |
+
values[key] = param_values
|
| 952 |
+
return values
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
async def request_body_to_args(
|
| 956 |
+
body_fields: list[ModelField],
|
| 957 |
+
received_body: dict[str, Any] | FormData | bytes | None,
|
| 958 |
+
embed_body_fields: bool,
|
| 959 |
+
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
| 960 |
+
values: dict[str, Any] = {}
|
| 961 |
+
errors: list[dict[str, Any]] = []
|
| 962 |
+
assert body_fields, "request_body_to_args() should be called with fields"
|
| 963 |
+
single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields
|
| 964 |
+
first_field = body_fields[0]
|
| 965 |
+
body_to_process = received_body
|
| 966 |
+
|
| 967 |
+
fields_to_extract: list[ModelField] = body_fields
|
| 968 |
+
|
| 969 |
+
if (
|
| 970 |
+
single_not_embedded_field
|
| 971 |
+
and lenient_issubclass(first_field.field_info.annotation, BaseModel)
|
| 972 |
+
and isinstance(received_body, FormData)
|
| 973 |
+
):
|
| 974 |
+
fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)
|
| 975 |
+
|
| 976 |
+
if isinstance(received_body, FormData):
|
| 977 |
+
body_to_process = await _extract_form_body(fields_to_extract, received_body)
|
| 978 |
+
|
| 979 |
+
if single_not_embedded_field:
|
| 980 |
+
loc: tuple[str, ...] = ("body",)
|
| 981 |
+
v_, errors_ = _validate_value_with_model_field(
|
| 982 |
+
field=first_field, value=body_to_process, values=values, loc=loc
|
| 983 |
+
)
|
| 984 |
+
return {first_field.name: v_}, errors_
|
| 985 |
+
for field in body_fields:
|
| 986 |
+
loc = ("body", get_validation_alias(field))
|
| 987 |
+
value: Any | None = None
|
| 988 |
+
if body_to_process is not None and not isinstance(body_to_process, bytes):
|
| 989 |
+
try:
|
| 990 |
+
value = body_to_process.get(get_validation_alias(field))
|
| 991 |
+
# If the received body is a list, not a dict
|
| 992 |
+
except AttributeError:
|
| 993 |
+
errors.append(get_missing_field_error(loc))
|
| 994 |
+
continue
|
| 995 |
+
v_, errors_ = _validate_value_with_model_field(
|
| 996 |
+
field=field, value=value, values=values, loc=loc
|
| 997 |
+
)
|
| 998 |
+
if errors_:
|
| 999 |
+
errors.extend(errors_)
|
| 1000 |
+
else:
|
| 1001 |
+
values[field.name] = v_
|
| 1002 |
+
return values, errors
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
def get_body_field(
|
| 1006 |
+
*, flat_dependant: Dependant, name: str, embed_body_fields: bool
|
| 1007 |
+
) -> ModelField | None:
|
| 1008 |
+
"""
|
| 1009 |
+
Get a ModelField representing the request body for a path operation, combining
|
| 1010 |
+
all body parameters into a single field if necessary.
|
| 1011 |
+
|
| 1012 |
+
Used to check if it's form data (with `isinstance(body_field, params.Form)`)
|
| 1013 |
+
or JSON and to generate the JSON Schema for a request body.
|
| 1014 |
+
|
| 1015 |
+
This is **not** used to validate/parse the request body, that's done with each
|
| 1016 |
+
individual body parameter.
|
| 1017 |
+
"""
|
| 1018 |
+
if not flat_dependant.body_params:
|
| 1019 |
+
return None
|
| 1020 |
+
first_param = flat_dependant.body_params[0]
|
| 1021 |
+
if not embed_body_fields:
|
| 1022 |
+
return first_param
|
| 1023 |
+
model_name = "Body_" + name
|
| 1024 |
+
BodyModel = create_body_model(
|
| 1025 |
+
fields=flat_dependant.body_params, model_name=model_name
|
| 1026 |
+
)
|
| 1027 |
+
required = any(
|
| 1028 |
+
True for f in flat_dependant.body_params if f.field_info.is_required()
|
| 1029 |
+
)
|
| 1030 |
+
BodyFieldInfo_kwargs: dict[str, Any] = {
|
| 1031 |
+
"annotation": BodyModel,
|
| 1032 |
+
"alias": "body",
|
| 1033 |
+
}
|
| 1034 |
+
if not required:
|
| 1035 |
+
BodyFieldInfo_kwargs["default"] = None
|
| 1036 |
+
if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params):
|
| 1037 |
+
BodyFieldInfo: type[params.Body] = params.File
|
| 1038 |
+
elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params):
|
| 1039 |
+
BodyFieldInfo = params.Form
|
| 1040 |
+
else:
|
| 1041 |
+
BodyFieldInfo = params.Body
|
| 1042 |
+
|
| 1043 |
+
body_param_media_types = [
|
| 1044 |
+
f.field_info.media_type
|
| 1045 |
+
for f in flat_dependant.body_params
|
| 1046 |
+
if isinstance(f.field_info, params.Body)
|
| 1047 |
+
]
|
| 1048 |
+
if len(set(body_param_media_types)) == 1:
|
| 1049 |
+
BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0]
|
| 1050 |
+
final_field = create_model_field(
|
| 1051 |
+
name="body",
|
| 1052 |
+
type_=BodyModel,
|
| 1053 |
+
alias="body",
|
| 1054 |
+
field_info=BodyFieldInfo(**BodyFieldInfo_kwargs),
|
| 1055 |
+
)
|
| 1056 |
+
return final_field
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
def get_validation_alias(field: ModelField) -> str:
|
| 1060 |
+
va = getattr(field, "validation_alias", None)
|
| 1061 |
+
return va or field.alias
|
lib/python3.11/site-packages/fastapi/encoders.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import datetime
|
| 3 |
+
from collections import defaultdict, deque
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from decimal import Decimal
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from ipaddress import (
|
| 8 |
+
IPv4Address,
|
| 9 |
+
IPv4Interface,
|
| 10 |
+
IPv4Network,
|
| 11 |
+
IPv6Address,
|
| 12 |
+
IPv6Interface,
|
| 13 |
+
IPv6Network,
|
| 14 |
+
)
|
| 15 |
+
from pathlib import Path, PurePath
|
| 16 |
+
from re import Pattern
|
| 17 |
+
from types import GeneratorType
|
| 18 |
+
from typing import Annotated, Any
|
| 19 |
+
from uuid import UUID
|
| 20 |
+
|
| 21 |
+
from annotated_doc import Doc
|
| 22 |
+
from fastapi.exceptions import PydanticV1NotSupportedError
|
| 23 |
+
from fastapi.types import IncEx
|
| 24 |
+
from pydantic import BaseModel
|
| 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 |
+
try:
|
| 35 |
+
# pydantic.color.Color is deprecated since v2.0b3, but supporting for bwd-compat
|
| 36 |
+
from pydantic.color import Color # ty: ignore[deprecated]
|
| 37 |
+
except ImportError: # pragma: no cover
|
| 38 |
+
|
| 39 |
+
class Color: # type: ignore[no-redef]
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
# Supporting the new Color format for newer versions of Pydantic
|
| 45 |
+
from pydantic_extra_types.color import Color as PyExtraColor
|
| 46 |
+
except ImportError: # pragma: no cover
|
| 47 |
+
|
| 48 |
+
class PyExtraColor: # type: ignore[no-redef]
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Taken from Pydantic v1 as is
|
| 53 |
+
def isoformat(o: datetime.date | datetime.time) -> str:
|
| 54 |
+
return o.isoformat()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Adapted from Pydantic v1
|
| 58 |
+
# TODO: pv2 should this return strings instead?
|
| 59 |
+
def decimal_encoder(dec_value: Decimal) -> int | float:
|
| 60 |
+
"""
|
| 61 |
+
Encodes a Decimal as int if there's no exponent, otherwise float
|
| 62 |
+
|
| 63 |
+
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
|
| 64 |
+
where an integer (but not int typed) is used. Encoding this as a float
|
| 65 |
+
results in failed round-tripping between encode and parse.
|
| 66 |
+
Our Id type is a prime example of this.
|
| 67 |
+
|
| 68 |
+
>>> decimal_encoder(Decimal("1.0"))
|
| 69 |
+
1.0
|
| 70 |
+
|
| 71 |
+
>>> decimal_encoder(Decimal("1"))
|
| 72 |
+
1
|
| 73 |
+
|
| 74 |
+
>>> decimal_encoder(Decimal("NaN"))
|
| 75 |
+
nan
|
| 76 |
+
"""
|
| 77 |
+
exponent = dec_value.as_tuple().exponent
|
| 78 |
+
if isinstance(exponent, int) and exponent >= 0:
|
| 79 |
+
return int(dec_value)
|
| 80 |
+
else:
|
| 81 |
+
return float(dec_value)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {
|
| 85 |
+
bytes: lambda o: o.decode(),
|
| 86 |
+
Color: str,
|
| 87 |
+
PyExtraColor: str,
|
| 88 |
+
datetime.date: isoformat,
|
| 89 |
+
datetime.datetime: isoformat,
|
| 90 |
+
datetime.time: isoformat,
|
| 91 |
+
datetime.timedelta: lambda td: td.total_seconds(),
|
| 92 |
+
Decimal: decimal_encoder,
|
| 93 |
+
Enum: lambda o: o.value,
|
| 94 |
+
frozenset: list,
|
| 95 |
+
deque: list,
|
| 96 |
+
GeneratorType: list,
|
| 97 |
+
IPv4Address: str,
|
| 98 |
+
IPv4Interface: str,
|
| 99 |
+
IPv4Network: str,
|
| 100 |
+
IPv6Address: str,
|
| 101 |
+
IPv6Interface: str,
|
| 102 |
+
IPv6Network: str,
|
| 103 |
+
NameEmail: str,
|
| 104 |
+
Path: str,
|
| 105 |
+
Pattern: lambda o: o.pattern,
|
| 106 |
+
SecretBytes: str,
|
| 107 |
+
SecretStr: str,
|
| 108 |
+
set: list,
|
| 109 |
+
UUID: str,
|
| 110 |
+
Url: str,
|
| 111 |
+
AnyUrl: str,
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def generate_encoders_by_class_tuples(
|
| 116 |
+
type_encoder_map: dict[Any, Callable[[Any], Any]],
|
| 117 |
+
) -> dict[Callable[[Any], Any], tuple[Any, ...]]:
|
| 118 |
+
encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict(
|
| 119 |
+
tuple
|
| 120 |
+
)
|
| 121 |
+
for type_, encoder in type_encoder_map.items():
|
| 122 |
+
encoders_by_class_tuples[encoder] += (type_,)
|
| 123 |
+
return encoders_by_class_tuples
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def jsonable_encoder(
|
| 130 |
+
obj: Annotated[
|
| 131 |
+
Any,
|
| 132 |
+
Doc(
|
| 133 |
+
"""
|
| 134 |
+
The input object to convert to JSON.
|
| 135 |
+
"""
|
| 136 |
+
),
|
| 137 |
+
],
|
| 138 |
+
include: Annotated[
|
| 139 |
+
IncEx | None,
|
| 140 |
+
Doc(
|
| 141 |
+
"""
|
| 142 |
+
Pydantic's `include` parameter, passed to Pydantic models to set the
|
| 143 |
+
fields to include.
|
| 144 |
+
"""
|
| 145 |
+
),
|
| 146 |
+
] = None,
|
| 147 |
+
exclude: Annotated[
|
| 148 |
+
IncEx | None,
|
| 149 |
+
Doc(
|
| 150 |
+
"""
|
| 151 |
+
Pydantic's `exclude` parameter, passed to Pydantic models to set the
|
| 152 |
+
fields to exclude.
|
| 153 |
+
"""
|
| 154 |
+
),
|
| 155 |
+
] = None,
|
| 156 |
+
by_alias: Annotated[
|
| 157 |
+
bool,
|
| 158 |
+
Doc(
|
| 159 |
+
"""
|
| 160 |
+
Pydantic's `by_alias` parameter, passed to Pydantic models to define if
|
| 161 |
+
the output should use the alias names (when provided) or the Python
|
| 162 |
+
attribute names. In an API, if you set an alias, it's probably because you
|
| 163 |
+
want to use it in the result, so you probably want to leave this set to
|
| 164 |
+
`True`.
|
| 165 |
+
"""
|
| 166 |
+
),
|
| 167 |
+
] = True,
|
| 168 |
+
exclude_unset: Annotated[
|
| 169 |
+
bool,
|
| 170 |
+
Doc(
|
| 171 |
+
"""
|
| 172 |
+
Pydantic's `exclude_unset` parameter, passed to Pydantic models to define
|
| 173 |
+
if it should exclude from the output the fields that were not explicitly
|
| 174 |
+
set (and that only had their default values).
|
| 175 |
+
"""
|
| 176 |
+
),
|
| 177 |
+
] = False,
|
| 178 |
+
exclude_defaults: Annotated[
|
| 179 |
+
bool,
|
| 180 |
+
Doc(
|
| 181 |
+
"""
|
| 182 |
+
Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define
|
| 183 |
+
if it should exclude from the output the fields that had the same default
|
| 184 |
+
value, even when they were explicitly set.
|
| 185 |
+
"""
|
| 186 |
+
),
|
| 187 |
+
] = False,
|
| 188 |
+
exclude_none: Annotated[
|
| 189 |
+
bool,
|
| 190 |
+
Doc(
|
| 191 |
+
"""
|
| 192 |
+
Pydantic's `exclude_none` parameter, passed to Pydantic models to define
|
| 193 |
+
if it should exclude from the output any fields that have a `None` value.
|
| 194 |
+
"""
|
| 195 |
+
),
|
| 196 |
+
] = False,
|
| 197 |
+
custom_encoder: Annotated[
|
| 198 |
+
dict[Any, Callable[[Any], Any]] | None,
|
| 199 |
+
Doc(
|
| 200 |
+
"""
|
| 201 |
+
Pydantic's `custom_encoder` parameter, passed to Pydantic models to define
|
| 202 |
+
a custom encoder.
|
| 203 |
+
"""
|
| 204 |
+
),
|
| 205 |
+
] = None,
|
| 206 |
+
sqlalchemy_safe: Annotated[
|
| 207 |
+
bool,
|
| 208 |
+
Doc(
|
| 209 |
+
"""
|
| 210 |
+
Exclude from the output any fields that start with the name `_sa`.
|
| 211 |
+
|
| 212 |
+
This is mainly a hack for compatibility with SQLAlchemy objects, they
|
| 213 |
+
store internal SQLAlchemy-specific state in attributes named with `_sa`,
|
| 214 |
+
and those objects can't (and shouldn't be) serialized to JSON.
|
| 215 |
+
"""
|
| 216 |
+
),
|
| 217 |
+
] = True,
|
| 218 |
+
) -> Any:
|
| 219 |
+
"""
|
| 220 |
+
Convert any object to something that can be encoded in JSON.
|
| 221 |
+
|
| 222 |
+
This is used internally by FastAPI to make sure anything you return can be
|
| 223 |
+
encoded as JSON before it is sent to the client.
|
| 224 |
+
|
| 225 |
+
You can also use it yourself, for example to convert objects before saving them
|
| 226 |
+
in a database that supports only JSON.
|
| 227 |
+
|
| 228 |
+
Read more about it in the
|
| 229 |
+
[FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
|
| 230 |
+
"""
|
| 231 |
+
custom_encoder = custom_encoder or {}
|
| 232 |
+
if custom_encoder:
|
| 233 |
+
if type(obj) in custom_encoder:
|
| 234 |
+
return custom_encoder[type(obj)](obj)
|
| 235 |
+
else:
|
| 236 |
+
for encoder_type, encoder_instance in custom_encoder.items():
|
| 237 |
+
if isinstance(obj, encoder_type):
|
| 238 |
+
return encoder_instance(obj)
|
| 239 |
+
if include is not None and not isinstance(include, (set, dict)):
|
| 240 |
+
include = set(include) # type: ignore[assignment] # ty: ignore[invalid-assignment]
|
| 241 |
+
if exclude is not None and not isinstance(exclude, (set, dict)):
|
| 242 |
+
exclude = set(exclude) # type: ignore[assignment] # ty: ignore[invalid-assignment]
|
| 243 |
+
if isinstance(obj, BaseModel):
|
| 244 |
+
obj_dict = obj.model_dump(
|
| 245 |
+
mode="json",
|
| 246 |
+
include=include,
|
| 247 |
+
exclude=exclude,
|
| 248 |
+
by_alias=by_alias,
|
| 249 |
+
exclude_unset=exclude_unset,
|
| 250 |
+
exclude_none=exclude_none,
|
| 251 |
+
exclude_defaults=exclude_defaults,
|
| 252 |
+
)
|
| 253 |
+
return jsonable_encoder(
|
| 254 |
+
obj_dict,
|
| 255 |
+
exclude_none=exclude_none,
|
| 256 |
+
exclude_defaults=exclude_defaults,
|
| 257 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 258 |
+
)
|
| 259 |
+
if dataclasses.is_dataclass(obj):
|
| 260 |
+
assert not isinstance(obj, type)
|
| 261 |
+
obj_dict = dataclasses.asdict(obj)
|
| 262 |
+
return jsonable_encoder(
|
| 263 |
+
obj_dict,
|
| 264 |
+
include=include,
|
| 265 |
+
exclude=exclude,
|
| 266 |
+
by_alias=by_alias,
|
| 267 |
+
exclude_unset=exclude_unset,
|
| 268 |
+
exclude_defaults=exclude_defaults,
|
| 269 |
+
exclude_none=exclude_none,
|
| 270 |
+
custom_encoder=custom_encoder,
|
| 271 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 272 |
+
)
|
| 273 |
+
if isinstance(obj, Enum):
|
| 274 |
+
return obj.value
|
| 275 |
+
if isinstance(obj, PurePath):
|
| 276 |
+
return str(obj)
|
| 277 |
+
if isinstance(obj, (str, int, float, type(None))):
|
| 278 |
+
return obj
|
| 279 |
+
if isinstance(obj, PydanticUndefinedType):
|
| 280 |
+
return None
|
| 281 |
+
if isinstance(obj, dict):
|
| 282 |
+
encoded_dict = {}
|
| 283 |
+
allowed_keys = set(obj.keys())
|
| 284 |
+
if include is not None:
|
| 285 |
+
allowed_keys &= set(include)
|
| 286 |
+
if exclude is not None:
|
| 287 |
+
allowed_keys -= set(exclude)
|
| 288 |
+
for key, value in obj.items():
|
| 289 |
+
if (
|
| 290 |
+
(
|
| 291 |
+
not sqlalchemy_safe
|
| 292 |
+
or (not isinstance(key, str))
|
| 293 |
+
or (not key.startswith("_sa"))
|
| 294 |
+
)
|
| 295 |
+
and (value is not None or not exclude_none)
|
| 296 |
+
and key in allowed_keys
|
| 297 |
+
):
|
| 298 |
+
encoded_key = jsonable_encoder(
|
| 299 |
+
key,
|
| 300 |
+
by_alias=by_alias,
|
| 301 |
+
exclude_unset=exclude_unset,
|
| 302 |
+
exclude_none=exclude_none,
|
| 303 |
+
custom_encoder=custom_encoder,
|
| 304 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 305 |
+
)
|
| 306 |
+
encoded_value = jsonable_encoder(
|
| 307 |
+
value,
|
| 308 |
+
by_alias=by_alias,
|
| 309 |
+
exclude_unset=exclude_unset,
|
| 310 |
+
exclude_none=exclude_none,
|
| 311 |
+
custom_encoder=custom_encoder,
|
| 312 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 313 |
+
)
|
| 314 |
+
encoded_dict[encoded_key] = encoded_value
|
| 315 |
+
return encoded_dict
|
| 316 |
+
if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
|
| 317 |
+
encoded_list = []
|
| 318 |
+
for item in obj:
|
| 319 |
+
encoded_list.append(
|
| 320 |
+
jsonable_encoder(
|
| 321 |
+
item,
|
| 322 |
+
include=include,
|
| 323 |
+
exclude=exclude,
|
| 324 |
+
by_alias=by_alias,
|
| 325 |
+
exclude_unset=exclude_unset,
|
| 326 |
+
exclude_defaults=exclude_defaults,
|
| 327 |
+
exclude_none=exclude_none,
|
| 328 |
+
custom_encoder=custom_encoder,
|
| 329 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 330 |
+
)
|
| 331 |
+
)
|
| 332 |
+
return encoded_list
|
| 333 |
+
|
| 334 |
+
if type(obj) in ENCODERS_BY_TYPE:
|
| 335 |
+
return ENCODERS_BY_TYPE[type(obj)](obj)
|
| 336 |
+
for encoder, classes_tuple in encoders_by_class_tuples.items():
|
| 337 |
+
if isinstance(obj, classes_tuple):
|
| 338 |
+
return encoder(obj)
|
| 339 |
+
if is_pydantic_v1_model_instance(obj):
|
| 340 |
+
raise PydanticV1NotSupportedError(
|
| 341 |
+
"pydantic.v1 models are no longer supported by FastAPI."
|
| 342 |
+
f" Please update the model {obj!r}."
|
| 343 |
+
)
|
| 344 |
+
try:
|
| 345 |
+
data = dict(obj)
|
| 346 |
+
except Exception as e:
|
| 347 |
+
errors: list[Exception] = []
|
| 348 |
+
errors.append(e)
|
| 349 |
+
try:
|
| 350 |
+
data = vars(obj)
|
| 351 |
+
except Exception as e:
|
| 352 |
+
errors.append(e)
|
| 353 |
+
raise ValueError(errors) from e
|
| 354 |
+
return jsonable_encoder(
|
| 355 |
+
data,
|
| 356 |
+
include=include,
|
| 357 |
+
exclude=exclude,
|
| 358 |
+
by_alias=by_alias,
|
| 359 |
+
exclude_unset=exclude_unset,
|
| 360 |
+
exclude_defaults=exclude_defaults,
|
| 361 |
+
exclude_none=exclude_none,
|
| 362 |
+
custom_encoder=custom_encoder,
|
| 363 |
+
sqlalchemy_safe=sqlalchemy_safe,
|
| 364 |
+
)
|
lib/python3.11/site-packages/fastapi/exception_handlers.py
ADDED
|
@@ -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 |
+
)
|
lib/python3.11/site-packages/fastapi/exceptions.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Mapping, Sequence
|
| 2 |
+
from typing import Annotated, Any, TypedDict
|
| 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 |
+
Read more about it in the
|
| 54 |
+
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)
|
| 55 |
+
"""
|
| 56 |
+
),
|
| 57 |
+
],
|
| 58 |
+
detail: Annotated[
|
| 59 |
+
Any,
|
| 60 |
+
Doc(
|
| 61 |
+
"""
|
| 62 |
+
Any data to be sent to the client in the `detail` key of the JSON
|
| 63 |
+
response.
|
| 64 |
+
|
| 65 |
+
Read more about it in the
|
| 66 |
+
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)
|
| 67 |
+
"""
|
| 68 |
+
),
|
| 69 |
+
] = None,
|
| 70 |
+
headers: Annotated[
|
| 71 |
+
Mapping[str, str] | None,
|
| 72 |
+
Doc(
|
| 73 |
+
"""
|
| 74 |
+
Any headers to send to the client in the response.
|
| 75 |
+
|
| 76 |
+
Read more about it in the
|
| 77 |
+
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
),
|
| 81 |
+
] = None,
|
| 82 |
+
) -> None:
|
| 83 |
+
super().__init__(status_code=status_code, detail=detail, headers=headers)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class WebSocketException(StarletteWebSocketException):
|
| 87 |
+
"""
|
| 88 |
+
A WebSocket exception you can raise in your own code to show errors to the client.
|
| 89 |
+
|
| 90 |
+
This is for client errors, invalid authentication, invalid data, etc. Not for server
|
| 91 |
+
errors in your code.
|
| 92 |
+
|
| 93 |
+
Read more about it in the
|
| 94 |
+
[FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| 95 |
+
|
| 96 |
+
## Example
|
| 97 |
+
|
| 98 |
+
```python
|
| 99 |
+
from typing import Annotated
|
| 100 |
+
|
| 101 |
+
from fastapi import (
|
| 102 |
+
Cookie,
|
| 103 |
+
FastAPI,
|
| 104 |
+
WebSocket,
|
| 105 |
+
WebSocketException,
|
| 106 |
+
status,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
app = FastAPI()
|
| 110 |
+
|
| 111 |
+
@app.websocket("/items/{item_id}/ws")
|
| 112 |
+
async def websocket_endpoint(
|
| 113 |
+
*,
|
| 114 |
+
websocket: WebSocket,
|
| 115 |
+
session: Annotated[str | None, Cookie()] = None,
|
| 116 |
+
item_id: str,
|
| 117 |
+
):
|
| 118 |
+
if session is None:
|
| 119 |
+
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
|
| 120 |
+
await websocket.accept()
|
| 121 |
+
while True:
|
| 122 |
+
data = await websocket.receive_text()
|
| 123 |
+
await websocket.send_text(f"Session cookie is: {session}")
|
| 124 |
+
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
|
| 125 |
+
```
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
code: Annotated[
|
| 131 |
+
int,
|
| 132 |
+
Doc(
|
| 133 |
+
"""
|
| 134 |
+
A closing code from the
|
| 135 |
+
[valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
|
| 136 |
+
"""
|
| 137 |
+
),
|
| 138 |
+
],
|
| 139 |
+
reason: Annotated[
|
| 140 |
+
str | None,
|
| 141 |
+
Doc(
|
| 142 |
+
"""
|
| 143 |
+
The reason to close the WebSocket connection.
|
| 144 |
+
|
| 145 |
+
It is UTF-8-encoded data. The interpretation of the reason is up to the
|
| 146 |
+
application, it is not specified by the WebSocket specification.
|
| 147 |
+
|
| 148 |
+
It could contain text that could be human-readable or interpretable
|
| 149 |
+
by the client code, etc.
|
| 150 |
+
"""
|
| 151 |
+
),
|
| 152 |
+
] = None,
|
| 153 |
+
) -> None:
|
| 154 |
+
super().__init__(code=code, reason=reason)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
RequestErrorModel: type[BaseModel] = create_model("Request")
|
| 158 |
+
WebSocketErrorModel: type[BaseModel] = create_model("WebSocket")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class FastAPIError(RuntimeError):
|
| 162 |
+
"""
|
| 163 |
+
A generic, FastAPI-specific error.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class DependencyScopeError(FastAPIError):
|
| 168 |
+
"""
|
| 169 |
+
A dependency declared that it depends on another dependency with an invalid
|
| 170 |
+
(narrower) scope.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class ValidationException(Exception):
|
| 175 |
+
def __init__(
|
| 176 |
+
self,
|
| 177 |
+
errors: Sequence[Any],
|
| 178 |
+
*,
|
| 179 |
+
endpoint_ctx: EndpointContext | None = None,
|
| 180 |
+
) -> None:
|
| 181 |
+
self._errors = errors
|
| 182 |
+
self.endpoint_ctx = endpoint_ctx
|
| 183 |
+
|
| 184 |
+
ctx = endpoint_ctx or {}
|
| 185 |
+
self.endpoint_function = ctx.get("function")
|
| 186 |
+
self.endpoint_path = ctx.get("path")
|
| 187 |
+
self.endpoint_file = ctx.get("file")
|
| 188 |
+
self.endpoint_line = ctx.get("line")
|
| 189 |
+
|
| 190 |
+
def errors(self) -> Sequence[Any]:
|
| 191 |
+
return self._errors
|
| 192 |
+
|
| 193 |
+
def _format_endpoint_context(self) -> str:
|
| 194 |
+
if not (self.endpoint_file and self.endpoint_line and self.endpoint_function):
|
| 195 |
+
if self.endpoint_path:
|
| 196 |
+
return f"\n Endpoint: {self.endpoint_path}"
|
| 197 |
+
return ""
|
| 198 |
+
|
| 199 |
+
context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}'
|
| 200 |
+
if self.endpoint_path:
|
| 201 |
+
context += f"\n {self.endpoint_path}"
|
| 202 |
+
return context
|
| 203 |
+
|
| 204 |
+
def __str__(self) -> str:
|
| 205 |
+
message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n"
|
| 206 |
+
for err in self._errors:
|
| 207 |
+
message += f" {err}\n"
|
| 208 |
+
message += self._format_endpoint_context()
|
| 209 |
+
return message.rstrip()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class RequestValidationError(ValidationException):
|
| 213 |
+
def __init__(
|
| 214 |
+
self,
|
| 215 |
+
errors: Sequence[Any],
|
| 216 |
+
*,
|
| 217 |
+
body: Any = None,
|
| 218 |
+
endpoint_ctx: EndpointContext | None = None,
|
| 219 |
+
) -> None:
|
| 220 |
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
| 221 |
+
self.body = body
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class WebSocketRequestValidationError(ValidationException):
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
errors: Sequence[Any],
|
| 228 |
+
*,
|
| 229 |
+
endpoint_ctx: EndpointContext | None = None,
|
| 230 |
+
) -> None:
|
| 231 |
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class ResponseValidationError(ValidationException):
|
| 235 |
+
def __init__(
|
| 236 |
+
self,
|
| 237 |
+
errors: Sequence[Any],
|
| 238 |
+
*,
|
| 239 |
+
body: Any = None,
|
| 240 |
+
endpoint_ctx: EndpointContext | None = None,
|
| 241 |
+
) -> None:
|
| 242 |
+
super().__init__(errors, endpoint_ctx=endpoint_ctx)
|
| 243 |
+
self.body = body
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class PydanticV1NotSupportedError(FastAPIError):
|
| 247 |
+
"""
|
| 248 |
+
A pydantic.v1 model is used, which is no longer supported.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class FastAPIDeprecationWarning(UserWarning):
|
| 253 |
+
"""
|
| 254 |
+
A custom deprecation warning as DeprecationWarning is ignored
|
| 255 |
+
Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
|
| 256 |
+
"""
|
lib/python3.11/site-packages/fastapi/logger.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
logger = logging.getLogger("fastapi")
|
lib/python3.11/site-packages/fastapi/middleware/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.middleware import Middleware as Middleware
|
lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py
ADDED
|
@@ -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)
|
lib/python3.11/site-packages/fastapi/param_functions.py
ADDED
|
@@ -0,0 +1,2460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 4 |
+
from annotated_doc import Doc
|
| 5 |
+
from fastapi import params
|
| 6 |
+
from fastapi._compat import Undefined
|
| 7 |
+
from fastapi.datastructures import _Unset
|
| 8 |
+
from fastapi.openapi.models import Example
|
| 9 |
+
from pydantic import AliasChoices, AliasPath
|
| 10 |
+
from typing_extensions import deprecated
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def Path( # noqa: N802
|
| 14 |
+
default: Annotated[
|
| 15 |
+
Any,
|
| 16 |
+
Doc(
|
| 17 |
+
"""
|
| 18 |
+
Default value if the parameter field is not set.
|
| 19 |
+
|
| 20 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 21 |
+
The parameter is available only for compatibility.
|
| 22 |
+
"""
|
| 23 |
+
),
|
| 24 |
+
] = ...,
|
| 25 |
+
*,
|
| 26 |
+
default_factory: Annotated[
|
| 27 |
+
Callable[[], Any] | None,
|
| 28 |
+
Doc(
|
| 29 |
+
"""
|
| 30 |
+
A callable to generate the default value.
|
| 31 |
+
|
| 32 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 33 |
+
The parameter is available only for compatibility.
|
| 34 |
+
"""
|
| 35 |
+
),
|
| 36 |
+
] = _Unset,
|
| 37 |
+
alias: Annotated[
|
| 38 |
+
str | None,
|
| 39 |
+
Doc(
|
| 40 |
+
"""
|
| 41 |
+
An alternative name for the parameter field.
|
| 42 |
+
|
| 43 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 44 |
+
It is particularly useful when you can't use the name you want because it
|
| 45 |
+
is a Python reserved keyword or similar.
|
| 46 |
+
"""
|
| 47 |
+
),
|
| 48 |
+
] = None,
|
| 49 |
+
alias_priority: Annotated[
|
| 50 |
+
int | None,
|
| 51 |
+
Doc(
|
| 52 |
+
"""
|
| 53 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 54 |
+
"""
|
| 55 |
+
),
|
| 56 |
+
] = _Unset,
|
| 57 |
+
validation_alias: Annotated[
|
| 58 |
+
str | AliasPath | AliasChoices | None,
|
| 59 |
+
Doc(
|
| 60 |
+
"""
|
| 61 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 62 |
+
allowed by the alias or set of aliases defined.
|
| 63 |
+
"""
|
| 64 |
+
),
|
| 65 |
+
] = None,
|
| 66 |
+
serialization_alias: Annotated[
|
| 67 |
+
str | None,
|
| 68 |
+
Doc(
|
| 69 |
+
"""
|
| 70 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 71 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 72 |
+
fields will be ignored at serialization time.
|
| 73 |
+
"""
|
| 74 |
+
),
|
| 75 |
+
] = None,
|
| 76 |
+
title: Annotated[
|
| 77 |
+
str | None,
|
| 78 |
+
Doc(
|
| 79 |
+
"""
|
| 80 |
+
Human-readable title.
|
| 81 |
+
|
| 82 |
+
Read more about it in the
|
| 83 |
+
[FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata)
|
| 84 |
+
"""
|
| 85 |
+
),
|
| 86 |
+
] = None,
|
| 87 |
+
description: Annotated[
|
| 88 |
+
str | None,
|
| 89 |
+
Doc(
|
| 90 |
+
"""
|
| 91 |
+
Human-readable description.
|
| 92 |
+
"""
|
| 93 |
+
),
|
| 94 |
+
] = None,
|
| 95 |
+
gt: Annotated[
|
| 96 |
+
float | None,
|
| 97 |
+
Doc(
|
| 98 |
+
"""
|
| 99 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 100 |
+
numbers.
|
| 101 |
+
|
| 102 |
+
Read more about it in the
|
| 103 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 104 |
+
"""
|
| 105 |
+
),
|
| 106 |
+
] = None,
|
| 107 |
+
ge: Annotated[
|
| 108 |
+
float | None,
|
| 109 |
+
Doc(
|
| 110 |
+
"""
|
| 111 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 112 |
+
this. Only applicable to numbers.
|
| 113 |
+
|
| 114 |
+
Read more about it in the
|
| 115 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 116 |
+
"""
|
| 117 |
+
),
|
| 118 |
+
] = None,
|
| 119 |
+
lt: Annotated[
|
| 120 |
+
float | None,
|
| 121 |
+
Doc(
|
| 122 |
+
"""
|
| 123 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 124 |
+
|
| 125 |
+
Read more about it in the
|
| 126 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 127 |
+
"""
|
| 128 |
+
),
|
| 129 |
+
] = None,
|
| 130 |
+
le: Annotated[
|
| 131 |
+
float | None,
|
| 132 |
+
Doc(
|
| 133 |
+
"""
|
| 134 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 135 |
+
Only applicable to numbers.
|
| 136 |
+
|
| 137 |
+
Read more about it in the
|
| 138 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 139 |
+
"""
|
| 140 |
+
),
|
| 141 |
+
] = None,
|
| 142 |
+
min_length: Annotated[
|
| 143 |
+
int | None,
|
| 144 |
+
Doc(
|
| 145 |
+
"""
|
| 146 |
+
Minimum length for strings.
|
| 147 |
+
"""
|
| 148 |
+
),
|
| 149 |
+
] = None,
|
| 150 |
+
max_length: Annotated[
|
| 151 |
+
int | None,
|
| 152 |
+
Doc(
|
| 153 |
+
"""
|
| 154 |
+
Maximum length for strings.
|
| 155 |
+
"""
|
| 156 |
+
),
|
| 157 |
+
] = None,
|
| 158 |
+
pattern: Annotated[
|
| 159 |
+
str | None,
|
| 160 |
+
Doc(
|
| 161 |
+
"""
|
| 162 |
+
RegEx pattern for strings.
|
| 163 |
+
"""
|
| 164 |
+
),
|
| 165 |
+
] = None,
|
| 166 |
+
regex: Annotated[
|
| 167 |
+
str | None,
|
| 168 |
+
Doc(
|
| 169 |
+
"""
|
| 170 |
+
RegEx pattern for strings.
|
| 171 |
+
"""
|
| 172 |
+
),
|
| 173 |
+
deprecated(
|
| 174 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 175 |
+
),
|
| 176 |
+
] = None,
|
| 177 |
+
discriminator: Annotated[
|
| 178 |
+
str | None,
|
| 179 |
+
Doc(
|
| 180 |
+
"""
|
| 181 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 182 |
+
"""
|
| 183 |
+
),
|
| 184 |
+
] = None,
|
| 185 |
+
strict: Annotated[
|
| 186 |
+
bool | None,
|
| 187 |
+
Doc(
|
| 188 |
+
"""
|
| 189 |
+
If `True`, strict validation is applied to the field.
|
| 190 |
+
"""
|
| 191 |
+
),
|
| 192 |
+
] = _Unset,
|
| 193 |
+
multiple_of: Annotated[
|
| 194 |
+
float | None,
|
| 195 |
+
Doc(
|
| 196 |
+
"""
|
| 197 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 198 |
+
"""
|
| 199 |
+
),
|
| 200 |
+
] = _Unset,
|
| 201 |
+
allow_inf_nan: Annotated[
|
| 202 |
+
bool | None,
|
| 203 |
+
Doc(
|
| 204 |
+
"""
|
| 205 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 206 |
+
"""
|
| 207 |
+
),
|
| 208 |
+
] = _Unset,
|
| 209 |
+
max_digits: Annotated[
|
| 210 |
+
int | None,
|
| 211 |
+
Doc(
|
| 212 |
+
"""
|
| 213 |
+
Maximum number of digits allowed for decimal values.
|
| 214 |
+
"""
|
| 215 |
+
),
|
| 216 |
+
] = _Unset,
|
| 217 |
+
decimal_places: Annotated[
|
| 218 |
+
int | None,
|
| 219 |
+
Doc(
|
| 220 |
+
"""
|
| 221 |
+
Maximum number of decimal places allowed for decimal values.
|
| 222 |
+
"""
|
| 223 |
+
),
|
| 224 |
+
] = _Unset,
|
| 225 |
+
examples: Annotated[
|
| 226 |
+
list[Any] | None,
|
| 227 |
+
Doc(
|
| 228 |
+
"""
|
| 229 |
+
Example values for this field.
|
| 230 |
+
|
| 231 |
+
Read more about it in the
|
| 232 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 233 |
+
"""
|
| 234 |
+
),
|
| 235 |
+
] = None,
|
| 236 |
+
example: Annotated[
|
| 237 |
+
Any | None,
|
| 238 |
+
deprecated(
|
| 239 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 240 |
+
"although still supported. Use examples instead."
|
| 241 |
+
),
|
| 242 |
+
] = _Unset,
|
| 243 |
+
openapi_examples: Annotated[
|
| 244 |
+
dict[str, Example] | None,
|
| 245 |
+
Doc(
|
| 246 |
+
"""
|
| 247 |
+
OpenAPI-specific examples.
|
| 248 |
+
|
| 249 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 250 |
+
|
| 251 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 252 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 253 |
+
use case for this.
|
| 254 |
+
|
| 255 |
+
Read more about it in the
|
| 256 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 257 |
+
"""
|
| 258 |
+
),
|
| 259 |
+
] = None,
|
| 260 |
+
deprecated: Annotated[
|
| 261 |
+
deprecated | str | bool | None,
|
| 262 |
+
Doc(
|
| 263 |
+
"""
|
| 264 |
+
Mark this parameter field as deprecated.
|
| 265 |
+
|
| 266 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 267 |
+
"""
|
| 268 |
+
),
|
| 269 |
+
] = None,
|
| 270 |
+
include_in_schema: Annotated[
|
| 271 |
+
bool,
|
| 272 |
+
Doc(
|
| 273 |
+
"""
|
| 274 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 275 |
+
You probably don't need it, but it's available.
|
| 276 |
+
|
| 277 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 278 |
+
"""
|
| 279 |
+
),
|
| 280 |
+
] = True,
|
| 281 |
+
json_schema_extra: Annotated[
|
| 282 |
+
dict[str, Any] | None,
|
| 283 |
+
Doc(
|
| 284 |
+
"""
|
| 285 |
+
Any additional JSON schema data.
|
| 286 |
+
"""
|
| 287 |
+
),
|
| 288 |
+
] = None,
|
| 289 |
+
**extra: Annotated[
|
| 290 |
+
Any,
|
| 291 |
+
Doc(
|
| 292 |
+
"""
|
| 293 |
+
Include extra fields used by the JSON Schema.
|
| 294 |
+
"""
|
| 295 |
+
),
|
| 296 |
+
deprecated(
|
| 297 |
+
"""
|
| 298 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 299 |
+
"""
|
| 300 |
+
),
|
| 301 |
+
],
|
| 302 |
+
) -> Any:
|
| 303 |
+
"""
|
| 304 |
+
Declare a path parameter for a *path operation*.
|
| 305 |
+
|
| 306 |
+
Read more about it in the
|
| 307 |
+
[FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).
|
| 308 |
+
|
| 309 |
+
```python
|
| 310 |
+
from typing import Annotated
|
| 311 |
+
|
| 312 |
+
from fastapi import FastAPI, Path
|
| 313 |
+
|
| 314 |
+
app = FastAPI()
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@app.get("/items/{item_id}")
|
| 318 |
+
async def read_items(
|
| 319 |
+
item_id: Annotated[int, Path(title="The ID of the item to get")],
|
| 320 |
+
):
|
| 321 |
+
return {"item_id": item_id}
|
| 322 |
+
```
|
| 323 |
+
"""
|
| 324 |
+
return params.Path(
|
| 325 |
+
default=default,
|
| 326 |
+
default_factory=default_factory,
|
| 327 |
+
alias=alias,
|
| 328 |
+
alias_priority=alias_priority,
|
| 329 |
+
validation_alias=validation_alias,
|
| 330 |
+
serialization_alias=serialization_alias,
|
| 331 |
+
title=title,
|
| 332 |
+
description=description,
|
| 333 |
+
gt=gt,
|
| 334 |
+
ge=ge,
|
| 335 |
+
lt=lt,
|
| 336 |
+
le=le,
|
| 337 |
+
min_length=min_length,
|
| 338 |
+
max_length=max_length,
|
| 339 |
+
pattern=pattern,
|
| 340 |
+
regex=regex,
|
| 341 |
+
discriminator=discriminator,
|
| 342 |
+
strict=strict,
|
| 343 |
+
multiple_of=multiple_of,
|
| 344 |
+
allow_inf_nan=allow_inf_nan,
|
| 345 |
+
max_digits=max_digits,
|
| 346 |
+
decimal_places=decimal_places,
|
| 347 |
+
example=example,
|
| 348 |
+
examples=examples,
|
| 349 |
+
openapi_examples=openapi_examples,
|
| 350 |
+
deprecated=deprecated,
|
| 351 |
+
include_in_schema=include_in_schema,
|
| 352 |
+
json_schema_extra=json_schema_extra,
|
| 353 |
+
**extra,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def Query( # noqa: N802
|
| 358 |
+
default: Annotated[
|
| 359 |
+
Any,
|
| 360 |
+
Doc(
|
| 361 |
+
"""
|
| 362 |
+
Default value if the parameter field is not set.
|
| 363 |
+
|
| 364 |
+
Read more about it in the
|
| 365 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value)
|
| 366 |
+
"""
|
| 367 |
+
),
|
| 368 |
+
] = Undefined,
|
| 369 |
+
*,
|
| 370 |
+
default_factory: Annotated[
|
| 371 |
+
Callable[[], Any] | None,
|
| 372 |
+
Doc(
|
| 373 |
+
"""
|
| 374 |
+
A callable to generate the default value.
|
| 375 |
+
|
| 376 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 377 |
+
The parameter is available only for compatibility.
|
| 378 |
+
"""
|
| 379 |
+
),
|
| 380 |
+
] = _Unset,
|
| 381 |
+
alias: Annotated[
|
| 382 |
+
str | None,
|
| 383 |
+
Doc(
|
| 384 |
+
"""
|
| 385 |
+
An alternative name for the parameter field.
|
| 386 |
+
|
| 387 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 388 |
+
It is particularly useful when you can't use the name you want because it
|
| 389 |
+
is a Python reserved keyword or similar.
|
| 390 |
+
|
| 391 |
+
Read more about it in the
|
| 392 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters)
|
| 393 |
+
"""
|
| 394 |
+
),
|
| 395 |
+
] = None,
|
| 396 |
+
alias_priority: Annotated[
|
| 397 |
+
int | None,
|
| 398 |
+
Doc(
|
| 399 |
+
"""
|
| 400 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 401 |
+
"""
|
| 402 |
+
),
|
| 403 |
+
] = _Unset,
|
| 404 |
+
validation_alias: Annotated[
|
| 405 |
+
str | AliasPath | AliasChoices | None,
|
| 406 |
+
Doc(
|
| 407 |
+
"""
|
| 408 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 409 |
+
allowed by the alias or set of aliases defined.
|
| 410 |
+
"""
|
| 411 |
+
),
|
| 412 |
+
] = None,
|
| 413 |
+
serialization_alias: Annotated[
|
| 414 |
+
str | None,
|
| 415 |
+
Doc(
|
| 416 |
+
"""
|
| 417 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 418 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 419 |
+
fields will be ignored at serialization time.
|
| 420 |
+
"""
|
| 421 |
+
),
|
| 422 |
+
] = None,
|
| 423 |
+
title: Annotated[
|
| 424 |
+
str | None,
|
| 425 |
+
Doc(
|
| 426 |
+
"""
|
| 427 |
+
Human-readable title.
|
| 428 |
+
|
| 429 |
+
Read more about it in the
|
| 430 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)
|
| 431 |
+
"""
|
| 432 |
+
),
|
| 433 |
+
] = None,
|
| 434 |
+
description: Annotated[
|
| 435 |
+
str | None,
|
| 436 |
+
Doc(
|
| 437 |
+
"""
|
| 438 |
+
Human-readable description.
|
| 439 |
+
|
| 440 |
+
Read more about it in the
|
| 441 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)
|
| 442 |
+
"""
|
| 443 |
+
),
|
| 444 |
+
] = None,
|
| 445 |
+
gt: Annotated[
|
| 446 |
+
float | None,
|
| 447 |
+
Doc(
|
| 448 |
+
"""
|
| 449 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 450 |
+
numbers.
|
| 451 |
+
|
| 452 |
+
Read more about it in the
|
| 453 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 454 |
+
"""
|
| 455 |
+
),
|
| 456 |
+
] = None,
|
| 457 |
+
ge: Annotated[
|
| 458 |
+
float | None,
|
| 459 |
+
Doc(
|
| 460 |
+
"""
|
| 461 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 462 |
+
this. Only applicable to numbers.
|
| 463 |
+
|
| 464 |
+
Read more about it in the
|
| 465 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 466 |
+
"""
|
| 467 |
+
),
|
| 468 |
+
] = None,
|
| 469 |
+
lt: Annotated[
|
| 470 |
+
float | None,
|
| 471 |
+
Doc(
|
| 472 |
+
"""
|
| 473 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 474 |
+
|
| 475 |
+
Read more about it in the
|
| 476 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 477 |
+
"""
|
| 478 |
+
),
|
| 479 |
+
] = None,
|
| 480 |
+
le: Annotated[
|
| 481 |
+
float | None,
|
| 482 |
+
Doc(
|
| 483 |
+
"""
|
| 484 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 485 |
+
Only applicable to numbers.
|
| 486 |
+
|
| 487 |
+
Read more about it in the
|
| 488 |
+
[FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)
|
| 489 |
+
"""
|
| 490 |
+
),
|
| 491 |
+
] = None,
|
| 492 |
+
min_length: Annotated[
|
| 493 |
+
int | None,
|
| 494 |
+
Doc(
|
| 495 |
+
"""
|
| 496 |
+
Minimum length for strings.
|
| 497 |
+
|
| 498 |
+
Read more about it in the
|
| 499 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)
|
| 500 |
+
"""
|
| 501 |
+
),
|
| 502 |
+
] = None,
|
| 503 |
+
max_length: Annotated[
|
| 504 |
+
int | None,
|
| 505 |
+
Doc(
|
| 506 |
+
"""
|
| 507 |
+
Maximum length for strings.
|
| 508 |
+
|
| 509 |
+
Read more about it in the
|
| 510 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)
|
| 511 |
+
"""
|
| 512 |
+
),
|
| 513 |
+
] = None,
|
| 514 |
+
pattern: Annotated[
|
| 515 |
+
str | None,
|
| 516 |
+
Doc(
|
| 517 |
+
"""
|
| 518 |
+
RegEx pattern for strings.
|
| 519 |
+
|
| 520 |
+
Read more about it in the
|
| 521 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions
|
| 522 |
+
"""
|
| 523 |
+
),
|
| 524 |
+
] = None,
|
| 525 |
+
regex: Annotated[
|
| 526 |
+
str | None,
|
| 527 |
+
Doc(
|
| 528 |
+
"""
|
| 529 |
+
RegEx pattern for strings.
|
| 530 |
+
"""
|
| 531 |
+
),
|
| 532 |
+
deprecated(
|
| 533 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 534 |
+
),
|
| 535 |
+
] = None,
|
| 536 |
+
discriminator: Annotated[
|
| 537 |
+
str | None,
|
| 538 |
+
Doc(
|
| 539 |
+
"""
|
| 540 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 541 |
+
"""
|
| 542 |
+
),
|
| 543 |
+
] = None,
|
| 544 |
+
strict: Annotated[
|
| 545 |
+
bool | None,
|
| 546 |
+
Doc(
|
| 547 |
+
"""
|
| 548 |
+
If `True`, strict validation is applied to the field.
|
| 549 |
+
"""
|
| 550 |
+
),
|
| 551 |
+
] = _Unset,
|
| 552 |
+
multiple_of: Annotated[
|
| 553 |
+
float | None,
|
| 554 |
+
Doc(
|
| 555 |
+
"""
|
| 556 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 557 |
+
"""
|
| 558 |
+
),
|
| 559 |
+
] = _Unset,
|
| 560 |
+
allow_inf_nan: Annotated[
|
| 561 |
+
bool | None,
|
| 562 |
+
Doc(
|
| 563 |
+
"""
|
| 564 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 565 |
+
"""
|
| 566 |
+
),
|
| 567 |
+
] = _Unset,
|
| 568 |
+
max_digits: Annotated[
|
| 569 |
+
int | None,
|
| 570 |
+
Doc(
|
| 571 |
+
"""
|
| 572 |
+
Maximum number of digits allowed for decimal values.
|
| 573 |
+
"""
|
| 574 |
+
),
|
| 575 |
+
] = _Unset,
|
| 576 |
+
decimal_places: Annotated[
|
| 577 |
+
int | None,
|
| 578 |
+
Doc(
|
| 579 |
+
"""
|
| 580 |
+
Maximum number of decimal places allowed for decimal values.
|
| 581 |
+
"""
|
| 582 |
+
),
|
| 583 |
+
] = _Unset,
|
| 584 |
+
examples: Annotated[
|
| 585 |
+
list[Any] | None,
|
| 586 |
+
Doc(
|
| 587 |
+
"""
|
| 588 |
+
Example values for this field.
|
| 589 |
+
|
| 590 |
+
Read more about it in the
|
| 591 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 592 |
+
"""
|
| 593 |
+
),
|
| 594 |
+
] = None,
|
| 595 |
+
example: Annotated[
|
| 596 |
+
Any | None,
|
| 597 |
+
deprecated(
|
| 598 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 599 |
+
"although still supported. Use examples instead."
|
| 600 |
+
),
|
| 601 |
+
] = _Unset,
|
| 602 |
+
openapi_examples: Annotated[
|
| 603 |
+
dict[str, Example] | None,
|
| 604 |
+
Doc(
|
| 605 |
+
"""
|
| 606 |
+
OpenAPI-specific examples.
|
| 607 |
+
|
| 608 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 609 |
+
|
| 610 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 611 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 612 |
+
use case for this.
|
| 613 |
+
|
| 614 |
+
Read more about it in the
|
| 615 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 616 |
+
"""
|
| 617 |
+
),
|
| 618 |
+
] = None,
|
| 619 |
+
deprecated: Annotated[
|
| 620 |
+
deprecated | str | bool | None,
|
| 621 |
+
Doc(
|
| 622 |
+
"""
|
| 623 |
+
Mark this parameter field as deprecated.
|
| 624 |
+
|
| 625 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 626 |
+
|
| 627 |
+
Read more about it in the
|
| 628 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters)
|
| 629 |
+
"""
|
| 630 |
+
),
|
| 631 |
+
] = None,
|
| 632 |
+
include_in_schema: Annotated[
|
| 633 |
+
bool,
|
| 634 |
+
Doc(
|
| 635 |
+
"""
|
| 636 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 637 |
+
You probably don't need it, but it's available.
|
| 638 |
+
|
| 639 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 640 |
+
|
| 641 |
+
Read more about it in the
|
| 642 |
+
[FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi
|
| 643 |
+
"""
|
| 644 |
+
),
|
| 645 |
+
] = True,
|
| 646 |
+
json_schema_extra: Annotated[
|
| 647 |
+
dict[str, Any] | None,
|
| 648 |
+
Doc(
|
| 649 |
+
"""
|
| 650 |
+
Any additional JSON schema data.
|
| 651 |
+
"""
|
| 652 |
+
),
|
| 653 |
+
] = None,
|
| 654 |
+
**extra: Annotated[
|
| 655 |
+
Any,
|
| 656 |
+
Doc(
|
| 657 |
+
"""
|
| 658 |
+
Include extra fields used by the JSON Schema.
|
| 659 |
+
"""
|
| 660 |
+
),
|
| 661 |
+
deprecated(
|
| 662 |
+
"""
|
| 663 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 664 |
+
"""
|
| 665 |
+
),
|
| 666 |
+
],
|
| 667 |
+
) -> Any:
|
| 668 |
+
return params.Query(
|
| 669 |
+
default=default,
|
| 670 |
+
default_factory=default_factory,
|
| 671 |
+
alias=alias,
|
| 672 |
+
alias_priority=alias_priority,
|
| 673 |
+
validation_alias=validation_alias,
|
| 674 |
+
serialization_alias=serialization_alias,
|
| 675 |
+
title=title,
|
| 676 |
+
description=description,
|
| 677 |
+
gt=gt,
|
| 678 |
+
ge=ge,
|
| 679 |
+
lt=lt,
|
| 680 |
+
le=le,
|
| 681 |
+
min_length=min_length,
|
| 682 |
+
max_length=max_length,
|
| 683 |
+
pattern=pattern,
|
| 684 |
+
regex=regex,
|
| 685 |
+
discriminator=discriminator,
|
| 686 |
+
strict=strict,
|
| 687 |
+
multiple_of=multiple_of,
|
| 688 |
+
allow_inf_nan=allow_inf_nan,
|
| 689 |
+
max_digits=max_digits,
|
| 690 |
+
decimal_places=decimal_places,
|
| 691 |
+
example=example,
|
| 692 |
+
examples=examples,
|
| 693 |
+
openapi_examples=openapi_examples,
|
| 694 |
+
deprecated=deprecated,
|
| 695 |
+
include_in_schema=include_in_schema,
|
| 696 |
+
json_schema_extra=json_schema_extra,
|
| 697 |
+
**extra,
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def Header( # noqa: N802
|
| 702 |
+
default: Annotated[
|
| 703 |
+
Any,
|
| 704 |
+
Doc(
|
| 705 |
+
"""
|
| 706 |
+
Default value if the parameter field is not set.
|
| 707 |
+
"""
|
| 708 |
+
),
|
| 709 |
+
] = Undefined,
|
| 710 |
+
*,
|
| 711 |
+
default_factory: Annotated[
|
| 712 |
+
Callable[[], Any] | None,
|
| 713 |
+
Doc(
|
| 714 |
+
"""
|
| 715 |
+
A callable to generate the default value.
|
| 716 |
+
|
| 717 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 718 |
+
The parameter is available only for compatibility.
|
| 719 |
+
"""
|
| 720 |
+
),
|
| 721 |
+
] = _Unset,
|
| 722 |
+
alias: Annotated[
|
| 723 |
+
str | None,
|
| 724 |
+
Doc(
|
| 725 |
+
"""
|
| 726 |
+
An alternative name for the parameter field.
|
| 727 |
+
|
| 728 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 729 |
+
It is particularly useful when you can't use the name you want because it
|
| 730 |
+
is a Python reserved keyword or similar.
|
| 731 |
+
"""
|
| 732 |
+
),
|
| 733 |
+
] = None,
|
| 734 |
+
alias_priority: Annotated[
|
| 735 |
+
int | None,
|
| 736 |
+
Doc(
|
| 737 |
+
"""
|
| 738 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 739 |
+
"""
|
| 740 |
+
),
|
| 741 |
+
] = _Unset,
|
| 742 |
+
validation_alias: Annotated[
|
| 743 |
+
str | AliasPath | AliasChoices | None,
|
| 744 |
+
Doc(
|
| 745 |
+
"""
|
| 746 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 747 |
+
allowed by the alias or set of aliases defined.
|
| 748 |
+
"""
|
| 749 |
+
),
|
| 750 |
+
] = None,
|
| 751 |
+
serialization_alias: Annotated[
|
| 752 |
+
str | None,
|
| 753 |
+
Doc(
|
| 754 |
+
"""
|
| 755 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 756 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 757 |
+
fields will be ignored at serialization time.
|
| 758 |
+
"""
|
| 759 |
+
),
|
| 760 |
+
] = None,
|
| 761 |
+
convert_underscores: Annotated[
|
| 762 |
+
bool,
|
| 763 |
+
Doc(
|
| 764 |
+
"""
|
| 765 |
+
Automatically convert underscores to hyphens in the parameter field name.
|
| 766 |
+
|
| 767 |
+
Read more about it in the
|
| 768 |
+
[FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion)
|
| 769 |
+
"""
|
| 770 |
+
),
|
| 771 |
+
] = True,
|
| 772 |
+
title: Annotated[
|
| 773 |
+
str | None,
|
| 774 |
+
Doc(
|
| 775 |
+
"""
|
| 776 |
+
Human-readable title.
|
| 777 |
+
"""
|
| 778 |
+
),
|
| 779 |
+
] = None,
|
| 780 |
+
description: Annotated[
|
| 781 |
+
str | None,
|
| 782 |
+
Doc(
|
| 783 |
+
"""
|
| 784 |
+
Human-readable description.
|
| 785 |
+
"""
|
| 786 |
+
),
|
| 787 |
+
] = None,
|
| 788 |
+
gt: Annotated[
|
| 789 |
+
float | None,
|
| 790 |
+
Doc(
|
| 791 |
+
"""
|
| 792 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 793 |
+
numbers.
|
| 794 |
+
"""
|
| 795 |
+
),
|
| 796 |
+
] = None,
|
| 797 |
+
ge: Annotated[
|
| 798 |
+
float | None,
|
| 799 |
+
Doc(
|
| 800 |
+
"""
|
| 801 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 802 |
+
this. Only applicable to numbers.
|
| 803 |
+
"""
|
| 804 |
+
),
|
| 805 |
+
] = None,
|
| 806 |
+
lt: Annotated[
|
| 807 |
+
float | None,
|
| 808 |
+
Doc(
|
| 809 |
+
"""
|
| 810 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 811 |
+
"""
|
| 812 |
+
),
|
| 813 |
+
] = None,
|
| 814 |
+
le: Annotated[
|
| 815 |
+
float | None,
|
| 816 |
+
Doc(
|
| 817 |
+
"""
|
| 818 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 819 |
+
Only applicable to numbers.
|
| 820 |
+
"""
|
| 821 |
+
),
|
| 822 |
+
] = None,
|
| 823 |
+
min_length: Annotated[
|
| 824 |
+
int | None,
|
| 825 |
+
Doc(
|
| 826 |
+
"""
|
| 827 |
+
Minimum length for strings.
|
| 828 |
+
"""
|
| 829 |
+
),
|
| 830 |
+
] = None,
|
| 831 |
+
max_length: Annotated[
|
| 832 |
+
int | None,
|
| 833 |
+
Doc(
|
| 834 |
+
"""
|
| 835 |
+
Maximum length for strings.
|
| 836 |
+
"""
|
| 837 |
+
),
|
| 838 |
+
] = None,
|
| 839 |
+
pattern: Annotated[
|
| 840 |
+
str | None,
|
| 841 |
+
Doc(
|
| 842 |
+
"""
|
| 843 |
+
RegEx pattern for strings.
|
| 844 |
+
"""
|
| 845 |
+
),
|
| 846 |
+
] = None,
|
| 847 |
+
regex: Annotated[
|
| 848 |
+
str | None,
|
| 849 |
+
Doc(
|
| 850 |
+
"""
|
| 851 |
+
RegEx pattern for strings.
|
| 852 |
+
"""
|
| 853 |
+
),
|
| 854 |
+
deprecated(
|
| 855 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 856 |
+
),
|
| 857 |
+
] = None,
|
| 858 |
+
discriminator: Annotated[
|
| 859 |
+
str | None,
|
| 860 |
+
Doc(
|
| 861 |
+
"""
|
| 862 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 863 |
+
"""
|
| 864 |
+
),
|
| 865 |
+
] = None,
|
| 866 |
+
strict: Annotated[
|
| 867 |
+
bool | None,
|
| 868 |
+
Doc(
|
| 869 |
+
"""
|
| 870 |
+
If `True`, strict validation is applied to the field.
|
| 871 |
+
"""
|
| 872 |
+
),
|
| 873 |
+
] = _Unset,
|
| 874 |
+
multiple_of: Annotated[
|
| 875 |
+
float | None,
|
| 876 |
+
Doc(
|
| 877 |
+
"""
|
| 878 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 879 |
+
"""
|
| 880 |
+
),
|
| 881 |
+
] = _Unset,
|
| 882 |
+
allow_inf_nan: Annotated[
|
| 883 |
+
bool | None,
|
| 884 |
+
Doc(
|
| 885 |
+
"""
|
| 886 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 887 |
+
"""
|
| 888 |
+
),
|
| 889 |
+
] = _Unset,
|
| 890 |
+
max_digits: Annotated[
|
| 891 |
+
int | None,
|
| 892 |
+
Doc(
|
| 893 |
+
"""
|
| 894 |
+
Maximum number of digits allowed for decimal values.
|
| 895 |
+
"""
|
| 896 |
+
),
|
| 897 |
+
] = _Unset,
|
| 898 |
+
decimal_places: Annotated[
|
| 899 |
+
int | None,
|
| 900 |
+
Doc(
|
| 901 |
+
"""
|
| 902 |
+
Maximum number of decimal places allowed for decimal values.
|
| 903 |
+
"""
|
| 904 |
+
),
|
| 905 |
+
] = _Unset,
|
| 906 |
+
examples: Annotated[
|
| 907 |
+
list[Any] | None,
|
| 908 |
+
Doc(
|
| 909 |
+
"""
|
| 910 |
+
Example values for this field.
|
| 911 |
+
|
| 912 |
+
Read more about it in the
|
| 913 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 914 |
+
"""
|
| 915 |
+
),
|
| 916 |
+
] = None,
|
| 917 |
+
example: Annotated[
|
| 918 |
+
Any | None,
|
| 919 |
+
deprecated(
|
| 920 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 921 |
+
"although still supported. Use examples instead."
|
| 922 |
+
),
|
| 923 |
+
] = _Unset,
|
| 924 |
+
openapi_examples: Annotated[
|
| 925 |
+
dict[str, Example] | None,
|
| 926 |
+
Doc(
|
| 927 |
+
"""
|
| 928 |
+
OpenAPI-specific examples.
|
| 929 |
+
|
| 930 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 931 |
+
|
| 932 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 933 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 934 |
+
use case for this.
|
| 935 |
+
|
| 936 |
+
Read more about it in the
|
| 937 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 938 |
+
"""
|
| 939 |
+
),
|
| 940 |
+
] = None,
|
| 941 |
+
deprecated: Annotated[
|
| 942 |
+
deprecated | str | bool | None,
|
| 943 |
+
Doc(
|
| 944 |
+
"""
|
| 945 |
+
Mark this parameter field as deprecated.
|
| 946 |
+
|
| 947 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 948 |
+
"""
|
| 949 |
+
),
|
| 950 |
+
] = None,
|
| 951 |
+
include_in_schema: Annotated[
|
| 952 |
+
bool,
|
| 953 |
+
Doc(
|
| 954 |
+
"""
|
| 955 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 956 |
+
You probably don't need it, but it's available.
|
| 957 |
+
|
| 958 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 959 |
+
"""
|
| 960 |
+
),
|
| 961 |
+
] = True,
|
| 962 |
+
json_schema_extra: Annotated[
|
| 963 |
+
dict[str, Any] | None,
|
| 964 |
+
Doc(
|
| 965 |
+
"""
|
| 966 |
+
Any additional JSON schema data.
|
| 967 |
+
"""
|
| 968 |
+
),
|
| 969 |
+
] = None,
|
| 970 |
+
**extra: Annotated[
|
| 971 |
+
Any,
|
| 972 |
+
Doc(
|
| 973 |
+
"""
|
| 974 |
+
Include extra fields used by the JSON Schema.
|
| 975 |
+
"""
|
| 976 |
+
),
|
| 977 |
+
deprecated(
|
| 978 |
+
"""
|
| 979 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 980 |
+
"""
|
| 981 |
+
),
|
| 982 |
+
],
|
| 983 |
+
) -> Any:
|
| 984 |
+
return params.Header(
|
| 985 |
+
default=default,
|
| 986 |
+
default_factory=default_factory,
|
| 987 |
+
alias=alias,
|
| 988 |
+
alias_priority=alias_priority,
|
| 989 |
+
validation_alias=validation_alias,
|
| 990 |
+
serialization_alias=serialization_alias,
|
| 991 |
+
convert_underscores=convert_underscores,
|
| 992 |
+
title=title,
|
| 993 |
+
description=description,
|
| 994 |
+
gt=gt,
|
| 995 |
+
ge=ge,
|
| 996 |
+
lt=lt,
|
| 997 |
+
le=le,
|
| 998 |
+
min_length=min_length,
|
| 999 |
+
max_length=max_length,
|
| 1000 |
+
pattern=pattern,
|
| 1001 |
+
regex=regex,
|
| 1002 |
+
discriminator=discriminator,
|
| 1003 |
+
strict=strict,
|
| 1004 |
+
multiple_of=multiple_of,
|
| 1005 |
+
allow_inf_nan=allow_inf_nan,
|
| 1006 |
+
max_digits=max_digits,
|
| 1007 |
+
decimal_places=decimal_places,
|
| 1008 |
+
example=example,
|
| 1009 |
+
examples=examples,
|
| 1010 |
+
openapi_examples=openapi_examples,
|
| 1011 |
+
deprecated=deprecated,
|
| 1012 |
+
include_in_schema=include_in_schema,
|
| 1013 |
+
json_schema_extra=json_schema_extra,
|
| 1014 |
+
**extra,
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def Cookie( # noqa: N802
|
| 1019 |
+
default: Annotated[
|
| 1020 |
+
Any,
|
| 1021 |
+
Doc(
|
| 1022 |
+
"""
|
| 1023 |
+
Default value if the parameter field is not set.
|
| 1024 |
+
"""
|
| 1025 |
+
),
|
| 1026 |
+
] = Undefined,
|
| 1027 |
+
*,
|
| 1028 |
+
default_factory: Annotated[
|
| 1029 |
+
Callable[[], Any] | None,
|
| 1030 |
+
Doc(
|
| 1031 |
+
"""
|
| 1032 |
+
A callable to generate the default value.
|
| 1033 |
+
|
| 1034 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 1035 |
+
The parameter is available only for compatibility.
|
| 1036 |
+
"""
|
| 1037 |
+
),
|
| 1038 |
+
] = _Unset,
|
| 1039 |
+
alias: Annotated[
|
| 1040 |
+
str | None,
|
| 1041 |
+
Doc(
|
| 1042 |
+
"""
|
| 1043 |
+
An alternative name for the parameter field.
|
| 1044 |
+
|
| 1045 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 1046 |
+
It is particularly useful when you can't use the name you want because it
|
| 1047 |
+
is a Python reserved keyword or similar.
|
| 1048 |
+
"""
|
| 1049 |
+
),
|
| 1050 |
+
] = None,
|
| 1051 |
+
alias_priority: Annotated[
|
| 1052 |
+
int | None,
|
| 1053 |
+
Doc(
|
| 1054 |
+
"""
|
| 1055 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 1056 |
+
"""
|
| 1057 |
+
),
|
| 1058 |
+
] = _Unset,
|
| 1059 |
+
validation_alias: Annotated[
|
| 1060 |
+
str | AliasPath | AliasChoices | None,
|
| 1061 |
+
Doc(
|
| 1062 |
+
"""
|
| 1063 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 1064 |
+
allowed by the alias or set of aliases defined.
|
| 1065 |
+
"""
|
| 1066 |
+
),
|
| 1067 |
+
] = None,
|
| 1068 |
+
serialization_alias: Annotated[
|
| 1069 |
+
str | None,
|
| 1070 |
+
Doc(
|
| 1071 |
+
"""
|
| 1072 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 1073 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 1074 |
+
fields will be ignored at serialization time.
|
| 1075 |
+
"""
|
| 1076 |
+
),
|
| 1077 |
+
] = None,
|
| 1078 |
+
title: Annotated[
|
| 1079 |
+
str | None,
|
| 1080 |
+
Doc(
|
| 1081 |
+
"""
|
| 1082 |
+
Human-readable title.
|
| 1083 |
+
"""
|
| 1084 |
+
),
|
| 1085 |
+
] = None,
|
| 1086 |
+
description: Annotated[
|
| 1087 |
+
str | None,
|
| 1088 |
+
Doc(
|
| 1089 |
+
"""
|
| 1090 |
+
Human-readable description.
|
| 1091 |
+
"""
|
| 1092 |
+
),
|
| 1093 |
+
] = None,
|
| 1094 |
+
gt: Annotated[
|
| 1095 |
+
float | None,
|
| 1096 |
+
Doc(
|
| 1097 |
+
"""
|
| 1098 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 1099 |
+
numbers.
|
| 1100 |
+
"""
|
| 1101 |
+
),
|
| 1102 |
+
] = None,
|
| 1103 |
+
ge: Annotated[
|
| 1104 |
+
float | None,
|
| 1105 |
+
Doc(
|
| 1106 |
+
"""
|
| 1107 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 1108 |
+
this. Only applicable to numbers.
|
| 1109 |
+
"""
|
| 1110 |
+
),
|
| 1111 |
+
] = None,
|
| 1112 |
+
lt: Annotated[
|
| 1113 |
+
float | None,
|
| 1114 |
+
Doc(
|
| 1115 |
+
"""
|
| 1116 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 1117 |
+
"""
|
| 1118 |
+
),
|
| 1119 |
+
] = None,
|
| 1120 |
+
le: Annotated[
|
| 1121 |
+
float | None,
|
| 1122 |
+
Doc(
|
| 1123 |
+
"""
|
| 1124 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 1125 |
+
Only applicable to numbers.
|
| 1126 |
+
"""
|
| 1127 |
+
),
|
| 1128 |
+
] = None,
|
| 1129 |
+
min_length: Annotated[
|
| 1130 |
+
int | None,
|
| 1131 |
+
Doc(
|
| 1132 |
+
"""
|
| 1133 |
+
Minimum length for strings.
|
| 1134 |
+
"""
|
| 1135 |
+
),
|
| 1136 |
+
] = None,
|
| 1137 |
+
max_length: Annotated[
|
| 1138 |
+
int | None,
|
| 1139 |
+
Doc(
|
| 1140 |
+
"""
|
| 1141 |
+
Maximum length for strings.
|
| 1142 |
+
"""
|
| 1143 |
+
),
|
| 1144 |
+
] = None,
|
| 1145 |
+
pattern: Annotated[
|
| 1146 |
+
str | None,
|
| 1147 |
+
Doc(
|
| 1148 |
+
"""
|
| 1149 |
+
RegEx pattern for strings.
|
| 1150 |
+
"""
|
| 1151 |
+
),
|
| 1152 |
+
] = None,
|
| 1153 |
+
regex: Annotated[
|
| 1154 |
+
str | None,
|
| 1155 |
+
Doc(
|
| 1156 |
+
"""
|
| 1157 |
+
RegEx pattern for strings.
|
| 1158 |
+
"""
|
| 1159 |
+
),
|
| 1160 |
+
deprecated(
|
| 1161 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 1162 |
+
),
|
| 1163 |
+
] = None,
|
| 1164 |
+
discriminator: Annotated[
|
| 1165 |
+
str | None,
|
| 1166 |
+
Doc(
|
| 1167 |
+
"""
|
| 1168 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 1169 |
+
"""
|
| 1170 |
+
),
|
| 1171 |
+
] = None,
|
| 1172 |
+
strict: Annotated[
|
| 1173 |
+
bool | None,
|
| 1174 |
+
Doc(
|
| 1175 |
+
"""
|
| 1176 |
+
If `True`, strict validation is applied to the field.
|
| 1177 |
+
"""
|
| 1178 |
+
),
|
| 1179 |
+
] = _Unset,
|
| 1180 |
+
multiple_of: Annotated[
|
| 1181 |
+
float | None,
|
| 1182 |
+
Doc(
|
| 1183 |
+
"""
|
| 1184 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 1185 |
+
"""
|
| 1186 |
+
),
|
| 1187 |
+
] = _Unset,
|
| 1188 |
+
allow_inf_nan: Annotated[
|
| 1189 |
+
bool | None,
|
| 1190 |
+
Doc(
|
| 1191 |
+
"""
|
| 1192 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 1193 |
+
"""
|
| 1194 |
+
),
|
| 1195 |
+
] = _Unset,
|
| 1196 |
+
max_digits: Annotated[
|
| 1197 |
+
int | None,
|
| 1198 |
+
Doc(
|
| 1199 |
+
"""
|
| 1200 |
+
Maximum number of digits allowed for decimal values.
|
| 1201 |
+
"""
|
| 1202 |
+
),
|
| 1203 |
+
] = _Unset,
|
| 1204 |
+
decimal_places: Annotated[
|
| 1205 |
+
int | None,
|
| 1206 |
+
Doc(
|
| 1207 |
+
"""
|
| 1208 |
+
Maximum number of decimal places allowed for decimal values.
|
| 1209 |
+
"""
|
| 1210 |
+
),
|
| 1211 |
+
] = _Unset,
|
| 1212 |
+
examples: Annotated[
|
| 1213 |
+
list[Any] | None,
|
| 1214 |
+
Doc(
|
| 1215 |
+
"""
|
| 1216 |
+
Example values for this field.
|
| 1217 |
+
|
| 1218 |
+
Read more about it in the
|
| 1219 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 1220 |
+
"""
|
| 1221 |
+
),
|
| 1222 |
+
] = None,
|
| 1223 |
+
example: Annotated[
|
| 1224 |
+
Any | None,
|
| 1225 |
+
deprecated(
|
| 1226 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 1227 |
+
"although still supported. Use examples instead."
|
| 1228 |
+
),
|
| 1229 |
+
] = _Unset,
|
| 1230 |
+
openapi_examples: Annotated[
|
| 1231 |
+
dict[str, Example] | None,
|
| 1232 |
+
Doc(
|
| 1233 |
+
"""
|
| 1234 |
+
OpenAPI-specific examples.
|
| 1235 |
+
|
| 1236 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 1237 |
+
|
| 1238 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 1239 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 1240 |
+
use case for this.
|
| 1241 |
+
|
| 1242 |
+
Read more about it in the
|
| 1243 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 1244 |
+
"""
|
| 1245 |
+
),
|
| 1246 |
+
] = None,
|
| 1247 |
+
deprecated: Annotated[
|
| 1248 |
+
deprecated | str | bool | None,
|
| 1249 |
+
Doc(
|
| 1250 |
+
"""
|
| 1251 |
+
Mark this parameter field as deprecated.
|
| 1252 |
+
|
| 1253 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 1254 |
+
"""
|
| 1255 |
+
),
|
| 1256 |
+
] = None,
|
| 1257 |
+
include_in_schema: Annotated[
|
| 1258 |
+
bool,
|
| 1259 |
+
Doc(
|
| 1260 |
+
"""
|
| 1261 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 1262 |
+
You probably don't need it, but it's available.
|
| 1263 |
+
|
| 1264 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 1265 |
+
"""
|
| 1266 |
+
),
|
| 1267 |
+
] = True,
|
| 1268 |
+
json_schema_extra: Annotated[
|
| 1269 |
+
dict[str, Any] | None,
|
| 1270 |
+
Doc(
|
| 1271 |
+
"""
|
| 1272 |
+
Any additional JSON schema data.
|
| 1273 |
+
"""
|
| 1274 |
+
),
|
| 1275 |
+
] = None,
|
| 1276 |
+
**extra: Annotated[
|
| 1277 |
+
Any,
|
| 1278 |
+
Doc(
|
| 1279 |
+
"""
|
| 1280 |
+
Include extra fields used by the JSON Schema.
|
| 1281 |
+
"""
|
| 1282 |
+
),
|
| 1283 |
+
deprecated(
|
| 1284 |
+
"""
|
| 1285 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 1286 |
+
"""
|
| 1287 |
+
),
|
| 1288 |
+
],
|
| 1289 |
+
) -> Any:
|
| 1290 |
+
return params.Cookie(
|
| 1291 |
+
default=default,
|
| 1292 |
+
default_factory=default_factory,
|
| 1293 |
+
alias=alias,
|
| 1294 |
+
alias_priority=alias_priority,
|
| 1295 |
+
validation_alias=validation_alias,
|
| 1296 |
+
serialization_alias=serialization_alias,
|
| 1297 |
+
title=title,
|
| 1298 |
+
description=description,
|
| 1299 |
+
gt=gt,
|
| 1300 |
+
ge=ge,
|
| 1301 |
+
lt=lt,
|
| 1302 |
+
le=le,
|
| 1303 |
+
min_length=min_length,
|
| 1304 |
+
max_length=max_length,
|
| 1305 |
+
pattern=pattern,
|
| 1306 |
+
regex=regex,
|
| 1307 |
+
discriminator=discriminator,
|
| 1308 |
+
strict=strict,
|
| 1309 |
+
multiple_of=multiple_of,
|
| 1310 |
+
allow_inf_nan=allow_inf_nan,
|
| 1311 |
+
max_digits=max_digits,
|
| 1312 |
+
decimal_places=decimal_places,
|
| 1313 |
+
example=example,
|
| 1314 |
+
examples=examples,
|
| 1315 |
+
openapi_examples=openapi_examples,
|
| 1316 |
+
deprecated=deprecated,
|
| 1317 |
+
include_in_schema=include_in_schema,
|
| 1318 |
+
json_schema_extra=json_schema_extra,
|
| 1319 |
+
**extra,
|
| 1320 |
+
)
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def Body( # noqa: N802
|
| 1324 |
+
default: Annotated[
|
| 1325 |
+
Any,
|
| 1326 |
+
Doc(
|
| 1327 |
+
"""
|
| 1328 |
+
Default value if the parameter field is not set.
|
| 1329 |
+
"""
|
| 1330 |
+
),
|
| 1331 |
+
] = Undefined,
|
| 1332 |
+
*,
|
| 1333 |
+
default_factory: Annotated[
|
| 1334 |
+
Callable[[], Any] | None,
|
| 1335 |
+
Doc(
|
| 1336 |
+
"""
|
| 1337 |
+
A callable to generate the default value.
|
| 1338 |
+
|
| 1339 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 1340 |
+
The parameter is available only for compatibility.
|
| 1341 |
+
"""
|
| 1342 |
+
),
|
| 1343 |
+
] = _Unset,
|
| 1344 |
+
embed: Annotated[
|
| 1345 |
+
bool | None,
|
| 1346 |
+
Doc(
|
| 1347 |
+
"""
|
| 1348 |
+
When `embed` is `True`, the parameter will be expected in a JSON body as a
|
| 1349 |
+
key instead of being the JSON body itself.
|
| 1350 |
+
|
| 1351 |
+
This happens automatically when more than one `Body` parameter is declared.
|
| 1352 |
+
|
| 1353 |
+
Read more about it in the
|
| 1354 |
+
[FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter).
|
| 1355 |
+
"""
|
| 1356 |
+
),
|
| 1357 |
+
] = None,
|
| 1358 |
+
media_type: Annotated[
|
| 1359 |
+
str,
|
| 1360 |
+
Doc(
|
| 1361 |
+
"""
|
| 1362 |
+
The media type of this parameter field. Changing it would affect the
|
| 1363 |
+
generated OpenAPI, but currently it doesn't affect the parsing of the data.
|
| 1364 |
+
"""
|
| 1365 |
+
),
|
| 1366 |
+
] = "application/json",
|
| 1367 |
+
alias: Annotated[
|
| 1368 |
+
str | None,
|
| 1369 |
+
Doc(
|
| 1370 |
+
"""
|
| 1371 |
+
An alternative name for the parameter field.
|
| 1372 |
+
|
| 1373 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 1374 |
+
It is particularly useful when you can't use the name you want because it
|
| 1375 |
+
is a Python reserved keyword or similar.
|
| 1376 |
+
"""
|
| 1377 |
+
),
|
| 1378 |
+
] = None,
|
| 1379 |
+
alias_priority: Annotated[
|
| 1380 |
+
int | None,
|
| 1381 |
+
Doc(
|
| 1382 |
+
"""
|
| 1383 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 1384 |
+
"""
|
| 1385 |
+
),
|
| 1386 |
+
] = _Unset,
|
| 1387 |
+
validation_alias: Annotated[
|
| 1388 |
+
str | AliasPath | AliasChoices | None,
|
| 1389 |
+
Doc(
|
| 1390 |
+
"""
|
| 1391 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 1392 |
+
allowed by the alias or set of aliases defined.
|
| 1393 |
+
"""
|
| 1394 |
+
),
|
| 1395 |
+
] = None,
|
| 1396 |
+
serialization_alias: Annotated[
|
| 1397 |
+
str | None,
|
| 1398 |
+
Doc(
|
| 1399 |
+
"""
|
| 1400 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 1401 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 1402 |
+
fields will be ignored at serialization time.
|
| 1403 |
+
"""
|
| 1404 |
+
),
|
| 1405 |
+
] = None,
|
| 1406 |
+
title: Annotated[
|
| 1407 |
+
str | None,
|
| 1408 |
+
Doc(
|
| 1409 |
+
"""
|
| 1410 |
+
Human-readable title.
|
| 1411 |
+
"""
|
| 1412 |
+
),
|
| 1413 |
+
] = None,
|
| 1414 |
+
description: Annotated[
|
| 1415 |
+
str | None,
|
| 1416 |
+
Doc(
|
| 1417 |
+
"""
|
| 1418 |
+
Human-readable description.
|
| 1419 |
+
"""
|
| 1420 |
+
),
|
| 1421 |
+
] = None,
|
| 1422 |
+
gt: Annotated[
|
| 1423 |
+
float | None,
|
| 1424 |
+
Doc(
|
| 1425 |
+
"""
|
| 1426 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 1427 |
+
numbers.
|
| 1428 |
+
"""
|
| 1429 |
+
),
|
| 1430 |
+
] = None,
|
| 1431 |
+
ge: Annotated[
|
| 1432 |
+
float | None,
|
| 1433 |
+
Doc(
|
| 1434 |
+
"""
|
| 1435 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 1436 |
+
this. Only applicable to numbers.
|
| 1437 |
+
"""
|
| 1438 |
+
),
|
| 1439 |
+
] = None,
|
| 1440 |
+
lt: Annotated[
|
| 1441 |
+
float | None,
|
| 1442 |
+
Doc(
|
| 1443 |
+
"""
|
| 1444 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 1445 |
+
"""
|
| 1446 |
+
),
|
| 1447 |
+
] = None,
|
| 1448 |
+
le: Annotated[
|
| 1449 |
+
float | None,
|
| 1450 |
+
Doc(
|
| 1451 |
+
"""
|
| 1452 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 1453 |
+
Only applicable to numbers.
|
| 1454 |
+
"""
|
| 1455 |
+
),
|
| 1456 |
+
] = None,
|
| 1457 |
+
min_length: Annotated[
|
| 1458 |
+
int | None,
|
| 1459 |
+
Doc(
|
| 1460 |
+
"""
|
| 1461 |
+
Minimum length for strings.
|
| 1462 |
+
"""
|
| 1463 |
+
),
|
| 1464 |
+
] = None,
|
| 1465 |
+
max_length: Annotated[
|
| 1466 |
+
int | None,
|
| 1467 |
+
Doc(
|
| 1468 |
+
"""
|
| 1469 |
+
Maximum length for strings.
|
| 1470 |
+
"""
|
| 1471 |
+
),
|
| 1472 |
+
] = None,
|
| 1473 |
+
pattern: Annotated[
|
| 1474 |
+
str | None,
|
| 1475 |
+
Doc(
|
| 1476 |
+
"""
|
| 1477 |
+
RegEx pattern for strings.
|
| 1478 |
+
"""
|
| 1479 |
+
),
|
| 1480 |
+
] = None,
|
| 1481 |
+
regex: Annotated[
|
| 1482 |
+
str | None,
|
| 1483 |
+
Doc(
|
| 1484 |
+
"""
|
| 1485 |
+
RegEx pattern for strings.
|
| 1486 |
+
"""
|
| 1487 |
+
),
|
| 1488 |
+
deprecated(
|
| 1489 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 1490 |
+
),
|
| 1491 |
+
] = None,
|
| 1492 |
+
discriminator: Annotated[
|
| 1493 |
+
str | None,
|
| 1494 |
+
Doc(
|
| 1495 |
+
"""
|
| 1496 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 1497 |
+
"""
|
| 1498 |
+
),
|
| 1499 |
+
] = None,
|
| 1500 |
+
strict: Annotated[
|
| 1501 |
+
bool | None,
|
| 1502 |
+
Doc(
|
| 1503 |
+
"""
|
| 1504 |
+
If `True`, strict validation is applied to the field.
|
| 1505 |
+
"""
|
| 1506 |
+
),
|
| 1507 |
+
] = _Unset,
|
| 1508 |
+
multiple_of: Annotated[
|
| 1509 |
+
float | None,
|
| 1510 |
+
Doc(
|
| 1511 |
+
"""
|
| 1512 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 1513 |
+
"""
|
| 1514 |
+
),
|
| 1515 |
+
] = _Unset,
|
| 1516 |
+
allow_inf_nan: Annotated[
|
| 1517 |
+
bool | None,
|
| 1518 |
+
Doc(
|
| 1519 |
+
"""
|
| 1520 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 1521 |
+
"""
|
| 1522 |
+
),
|
| 1523 |
+
] = _Unset,
|
| 1524 |
+
max_digits: Annotated[
|
| 1525 |
+
int | None,
|
| 1526 |
+
Doc(
|
| 1527 |
+
"""
|
| 1528 |
+
Maximum number of digits allowed for decimal values.
|
| 1529 |
+
"""
|
| 1530 |
+
),
|
| 1531 |
+
] = _Unset,
|
| 1532 |
+
decimal_places: Annotated[
|
| 1533 |
+
int | None,
|
| 1534 |
+
Doc(
|
| 1535 |
+
"""
|
| 1536 |
+
Maximum number of decimal places allowed for decimal values.
|
| 1537 |
+
"""
|
| 1538 |
+
),
|
| 1539 |
+
] = _Unset,
|
| 1540 |
+
examples: Annotated[
|
| 1541 |
+
list[Any] | None,
|
| 1542 |
+
Doc(
|
| 1543 |
+
"""
|
| 1544 |
+
Example values for this field.
|
| 1545 |
+
|
| 1546 |
+
Read more about it in the
|
| 1547 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 1548 |
+
"""
|
| 1549 |
+
),
|
| 1550 |
+
] = None,
|
| 1551 |
+
example: Annotated[
|
| 1552 |
+
Any | None,
|
| 1553 |
+
deprecated(
|
| 1554 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 1555 |
+
"although still supported. Use examples instead."
|
| 1556 |
+
),
|
| 1557 |
+
] = _Unset,
|
| 1558 |
+
openapi_examples: Annotated[
|
| 1559 |
+
dict[str, Example] | None,
|
| 1560 |
+
Doc(
|
| 1561 |
+
"""
|
| 1562 |
+
OpenAPI-specific examples.
|
| 1563 |
+
|
| 1564 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 1565 |
+
|
| 1566 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 1567 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 1568 |
+
use case for this.
|
| 1569 |
+
|
| 1570 |
+
Read more about it in the
|
| 1571 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 1572 |
+
"""
|
| 1573 |
+
),
|
| 1574 |
+
] = None,
|
| 1575 |
+
deprecated: Annotated[
|
| 1576 |
+
deprecated | str | bool | None,
|
| 1577 |
+
Doc(
|
| 1578 |
+
"""
|
| 1579 |
+
Mark this parameter field as deprecated.
|
| 1580 |
+
|
| 1581 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 1582 |
+
"""
|
| 1583 |
+
),
|
| 1584 |
+
] = None,
|
| 1585 |
+
include_in_schema: Annotated[
|
| 1586 |
+
bool,
|
| 1587 |
+
Doc(
|
| 1588 |
+
"""
|
| 1589 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 1590 |
+
You probably don't need it, but it's available.
|
| 1591 |
+
|
| 1592 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 1593 |
+
"""
|
| 1594 |
+
),
|
| 1595 |
+
] = True,
|
| 1596 |
+
json_schema_extra: Annotated[
|
| 1597 |
+
dict[str, Any] | None,
|
| 1598 |
+
Doc(
|
| 1599 |
+
"""
|
| 1600 |
+
Any additional JSON schema data.
|
| 1601 |
+
"""
|
| 1602 |
+
),
|
| 1603 |
+
] = None,
|
| 1604 |
+
**extra: Annotated[
|
| 1605 |
+
Any,
|
| 1606 |
+
Doc(
|
| 1607 |
+
"""
|
| 1608 |
+
Include extra fields used by the JSON Schema.
|
| 1609 |
+
"""
|
| 1610 |
+
),
|
| 1611 |
+
deprecated(
|
| 1612 |
+
"""
|
| 1613 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 1614 |
+
"""
|
| 1615 |
+
),
|
| 1616 |
+
],
|
| 1617 |
+
) -> Any:
|
| 1618 |
+
return params.Body(
|
| 1619 |
+
default=default,
|
| 1620 |
+
default_factory=default_factory,
|
| 1621 |
+
embed=embed,
|
| 1622 |
+
media_type=media_type,
|
| 1623 |
+
alias=alias,
|
| 1624 |
+
alias_priority=alias_priority,
|
| 1625 |
+
validation_alias=validation_alias,
|
| 1626 |
+
serialization_alias=serialization_alias,
|
| 1627 |
+
title=title,
|
| 1628 |
+
description=description,
|
| 1629 |
+
gt=gt,
|
| 1630 |
+
ge=ge,
|
| 1631 |
+
lt=lt,
|
| 1632 |
+
le=le,
|
| 1633 |
+
min_length=min_length,
|
| 1634 |
+
max_length=max_length,
|
| 1635 |
+
pattern=pattern,
|
| 1636 |
+
regex=regex,
|
| 1637 |
+
discriminator=discriminator,
|
| 1638 |
+
strict=strict,
|
| 1639 |
+
multiple_of=multiple_of,
|
| 1640 |
+
allow_inf_nan=allow_inf_nan,
|
| 1641 |
+
max_digits=max_digits,
|
| 1642 |
+
decimal_places=decimal_places,
|
| 1643 |
+
example=example,
|
| 1644 |
+
examples=examples,
|
| 1645 |
+
openapi_examples=openapi_examples,
|
| 1646 |
+
deprecated=deprecated,
|
| 1647 |
+
include_in_schema=include_in_schema,
|
| 1648 |
+
json_schema_extra=json_schema_extra,
|
| 1649 |
+
**extra,
|
| 1650 |
+
)
|
| 1651 |
+
|
| 1652 |
+
|
| 1653 |
+
def Form( # noqa: N802
|
| 1654 |
+
default: Annotated[
|
| 1655 |
+
Any,
|
| 1656 |
+
Doc(
|
| 1657 |
+
"""
|
| 1658 |
+
Default value if the parameter field is not set.
|
| 1659 |
+
"""
|
| 1660 |
+
),
|
| 1661 |
+
] = Undefined,
|
| 1662 |
+
*,
|
| 1663 |
+
default_factory: Annotated[
|
| 1664 |
+
Callable[[], Any] | None,
|
| 1665 |
+
Doc(
|
| 1666 |
+
"""
|
| 1667 |
+
A callable to generate the default value.
|
| 1668 |
+
|
| 1669 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 1670 |
+
The parameter is available only for compatibility.
|
| 1671 |
+
"""
|
| 1672 |
+
),
|
| 1673 |
+
] = _Unset,
|
| 1674 |
+
media_type: Annotated[
|
| 1675 |
+
str,
|
| 1676 |
+
Doc(
|
| 1677 |
+
"""
|
| 1678 |
+
The media type of this parameter field. Changing it would affect the
|
| 1679 |
+
generated OpenAPI, but currently it doesn't affect the parsing of the data.
|
| 1680 |
+
"""
|
| 1681 |
+
),
|
| 1682 |
+
] = "application/x-www-form-urlencoded",
|
| 1683 |
+
alias: Annotated[
|
| 1684 |
+
str | None,
|
| 1685 |
+
Doc(
|
| 1686 |
+
"""
|
| 1687 |
+
An alternative name for the parameter field.
|
| 1688 |
+
|
| 1689 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 1690 |
+
It is particularly useful when you can't use the name you want because it
|
| 1691 |
+
is a Python reserved keyword or similar.
|
| 1692 |
+
"""
|
| 1693 |
+
),
|
| 1694 |
+
] = None,
|
| 1695 |
+
alias_priority: Annotated[
|
| 1696 |
+
int | None,
|
| 1697 |
+
Doc(
|
| 1698 |
+
"""
|
| 1699 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 1700 |
+
"""
|
| 1701 |
+
),
|
| 1702 |
+
] = _Unset,
|
| 1703 |
+
validation_alias: Annotated[
|
| 1704 |
+
str | AliasPath | AliasChoices | None,
|
| 1705 |
+
Doc(
|
| 1706 |
+
"""
|
| 1707 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 1708 |
+
allowed by the alias or set of aliases defined.
|
| 1709 |
+
"""
|
| 1710 |
+
),
|
| 1711 |
+
] = None,
|
| 1712 |
+
serialization_alias: Annotated[
|
| 1713 |
+
str | None,
|
| 1714 |
+
Doc(
|
| 1715 |
+
"""
|
| 1716 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 1717 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 1718 |
+
fields will be ignored at serialization time.
|
| 1719 |
+
"""
|
| 1720 |
+
),
|
| 1721 |
+
] = None,
|
| 1722 |
+
title: Annotated[
|
| 1723 |
+
str | None,
|
| 1724 |
+
Doc(
|
| 1725 |
+
"""
|
| 1726 |
+
Human-readable title.
|
| 1727 |
+
"""
|
| 1728 |
+
),
|
| 1729 |
+
] = None,
|
| 1730 |
+
description: Annotated[
|
| 1731 |
+
str | None,
|
| 1732 |
+
Doc(
|
| 1733 |
+
"""
|
| 1734 |
+
Human-readable description.
|
| 1735 |
+
"""
|
| 1736 |
+
),
|
| 1737 |
+
] = None,
|
| 1738 |
+
gt: Annotated[
|
| 1739 |
+
float | None,
|
| 1740 |
+
Doc(
|
| 1741 |
+
"""
|
| 1742 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 1743 |
+
numbers.
|
| 1744 |
+
"""
|
| 1745 |
+
),
|
| 1746 |
+
] = None,
|
| 1747 |
+
ge: Annotated[
|
| 1748 |
+
float | None,
|
| 1749 |
+
Doc(
|
| 1750 |
+
"""
|
| 1751 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 1752 |
+
this. Only applicable to numbers.
|
| 1753 |
+
"""
|
| 1754 |
+
),
|
| 1755 |
+
] = None,
|
| 1756 |
+
lt: Annotated[
|
| 1757 |
+
float | None,
|
| 1758 |
+
Doc(
|
| 1759 |
+
"""
|
| 1760 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 1761 |
+
"""
|
| 1762 |
+
),
|
| 1763 |
+
] = None,
|
| 1764 |
+
le: Annotated[
|
| 1765 |
+
float | None,
|
| 1766 |
+
Doc(
|
| 1767 |
+
"""
|
| 1768 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 1769 |
+
Only applicable to numbers.
|
| 1770 |
+
"""
|
| 1771 |
+
),
|
| 1772 |
+
] = None,
|
| 1773 |
+
min_length: Annotated[
|
| 1774 |
+
int | None,
|
| 1775 |
+
Doc(
|
| 1776 |
+
"""
|
| 1777 |
+
Minimum length for strings.
|
| 1778 |
+
"""
|
| 1779 |
+
),
|
| 1780 |
+
] = None,
|
| 1781 |
+
max_length: Annotated[
|
| 1782 |
+
int | None,
|
| 1783 |
+
Doc(
|
| 1784 |
+
"""
|
| 1785 |
+
Maximum length for strings.
|
| 1786 |
+
"""
|
| 1787 |
+
),
|
| 1788 |
+
] = None,
|
| 1789 |
+
pattern: Annotated[
|
| 1790 |
+
str | None,
|
| 1791 |
+
Doc(
|
| 1792 |
+
"""
|
| 1793 |
+
RegEx pattern for strings.
|
| 1794 |
+
"""
|
| 1795 |
+
),
|
| 1796 |
+
] = None,
|
| 1797 |
+
regex: Annotated[
|
| 1798 |
+
str | None,
|
| 1799 |
+
Doc(
|
| 1800 |
+
"""
|
| 1801 |
+
RegEx pattern for strings.
|
| 1802 |
+
"""
|
| 1803 |
+
),
|
| 1804 |
+
deprecated(
|
| 1805 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 1806 |
+
),
|
| 1807 |
+
] = None,
|
| 1808 |
+
discriminator: Annotated[
|
| 1809 |
+
str | None,
|
| 1810 |
+
Doc(
|
| 1811 |
+
"""
|
| 1812 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 1813 |
+
"""
|
| 1814 |
+
),
|
| 1815 |
+
] = None,
|
| 1816 |
+
strict: Annotated[
|
| 1817 |
+
bool | None,
|
| 1818 |
+
Doc(
|
| 1819 |
+
"""
|
| 1820 |
+
If `True`, strict validation is applied to the field.
|
| 1821 |
+
"""
|
| 1822 |
+
),
|
| 1823 |
+
] = _Unset,
|
| 1824 |
+
multiple_of: Annotated[
|
| 1825 |
+
float | None,
|
| 1826 |
+
Doc(
|
| 1827 |
+
"""
|
| 1828 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 1829 |
+
"""
|
| 1830 |
+
),
|
| 1831 |
+
] = _Unset,
|
| 1832 |
+
allow_inf_nan: Annotated[
|
| 1833 |
+
bool | None,
|
| 1834 |
+
Doc(
|
| 1835 |
+
"""
|
| 1836 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 1837 |
+
"""
|
| 1838 |
+
),
|
| 1839 |
+
] = _Unset,
|
| 1840 |
+
max_digits: Annotated[
|
| 1841 |
+
int | None,
|
| 1842 |
+
Doc(
|
| 1843 |
+
"""
|
| 1844 |
+
Maximum number of digits allowed for decimal values.
|
| 1845 |
+
"""
|
| 1846 |
+
),
|
| 1847 |
+
] = _Unset,
|
| 1848 |
+
decimal_places: Annotated[
|
| 1849 |
+
int | None,
|
| 1850 |
+
Doc(
|
| 1851 |
+
"""
|
| 1852 |
+
Maximum number of decimal places allowed for decimal values.
|
| 1853 |
+
"""
|
| 1854 |
+
),
|
| 1855 |
+
] = _Unset,
|
| 1856 |
+
examples: Annotated[
|
| 1857 |
+
list[Any] | None,
|
| 1858 |
+
Doc(
|
| 1859 |
+
"""
|
| 1860 |
+
Example values for this field.
|
| 1861 |
+
|
| 1862 |
+
Read more about it in the
|
| 1863 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 1864 |
+
"""
|
| 1865 |
+
),
|
| 1866 |
+
] = None,
|
| 1867 |
+
example: Annotated[
|
| 1868 |
+
Any | None,
|
| 1869 |
+
deprecated(
|
| 1870 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 1871 |
+
"although still supported. Use examples instead."
|
| 1872 |
+
),
|
| 1873 |
+
] = _Unset,
|
| 1874 |
+
openapi_examples: Annotated[
|
| 1875 |
+
dict[str, Example] | None,
|
| 1876 |
+
Doc(
|
| 1877 |
+
"""
|
| 1878 |
+
OpenAPI-specific examples.
|
| 1879 |
+
|
| 1880 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 1881 |
+
|
| 1882 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 1883 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 1884 |
+
use case for this.
|
| 1885 |
+
|
| 1886 |
+
Read more about it in the
|
| 1887 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 1888 |
+
"""
|
| 1889 |
+
),
|
| 1890 |
+
] = None,
|
| 1891 |
+
deprecated: Annotated[
|
| 1892 |
+
deprecated | str | bool | None,
|
| 1893 |
+
Doc(
|
| 1894 |
+
"""
|
| 1895 |
+
Mark this parameter field as deprecated.
|
| 1896 |
+
|
| 1897 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 1898 |
+
"""
|
| 1899 |
+
),
|
| 1900 |
+
] = None,
|
| 1901 |
+
include_in_schema: Annotated[
|
| 1902 |
+
bool,
|
| 1903 |
+
Doc(
|
| 1904 |
+
"""
|
| 1905 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 1906 |
+
You probably don't need it, but it's available.
|
| 1907 |
+
|
| 1908 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 1909 |
+
"""
|
| 1910 |
+
),
|
| 1911 |
+
] = True,
|
| 1912 |
+
json_schema_extra: Annotated[
|
| 1913 |
+
dict[str, Any] | None,
|
| 1914 |
+
Doc(
|
| 1915 |
+
"""
|
| 1916 |
+
Any additional JSON schema data.
|
| 1917 |
+
"""
|
| 1918 |
+
),
|
| 1919 |
+
] = None,
|
| 1920 |
+
**extra: Annotated[
|
| 1921 |
+
Any,
|
| 1922 |
+
Doc(
|
| 1923 |
+
"""
|
| 1924 |
+
Include extra fields used by the JSON Schema.
|
| 1925 |
+
"""
|
| 1926 |
+
),
|
| 1927 |
+
deprecated(
|
| 1928 |
+
"""
|
| 1929 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 1930 |
+
"""
|
| 1931 |
+
),
|
| 1932 |
+
],
|
| 1933 |
+
) -> Any:
|
| 1934 |
+
return params.Form(
|
| 1935 |
+
default=default,
|
| 1936 |
+
default_factory=default_factory,
|
| 1937 |
+
media_type=media_type,
|
| 1938 |
+
alias=alias,
|
| 1939 |
+
alias_priority=alias_priority,
|
| 1940 |
+
validation_alias=validation_alias,
|
| 1941 |
+
serialization_alias=serialization_alias,
|
| 1942 |
+
title=title,
|
| 1943 |
+
description=description,
|
| 1944 |
+
gt=gt,
|
| 1945 |
+
ge=ge,
|
| 1946 |
+
lt=lt,
|
| 1947 |
+
le=le,
|
| 1948 |
+
min_length=min_length,
|
| 1949 |
+
max_length=max_length,
|
| 1950 |
+
pattern=pattern,
|
| 1951 |
+
regex=regex,
|
| 1952 |
+
discriminator=discriminator,
|
| 1953 |
+
strict=strict,
|
| 1954 |
+
multiple_of=multiple_of,
|
| 1955 |
+
allow_inf_nan=allow_inf_nan,
|
| 1956 |
+
max_digits=max_digits,
|
| 1957 |
+
decimal_places=decimal_places,
|
| 1958 |
+
example=example,
|
| 1959 |
+
examples=examples,
|
| 1960 |
+
openapi_examples=openapi_examples,
|
| 1961 |
+
deprecated=deprecated,
|
| 1962 |
+
include_in_schema=include_in_schema,
|
| 1963 |
+
json_schema_extra=json_schema_extra,
|
| 1964 |
+
**extra,
|
| 1965 |
+
)
|
| 1966 |
+
|
| 1967 |
+
|
| 1968 |
+
def File( # noqa: N802
|
| 1969 |
+
default: Annotated[
|
| 1970 |
+
Any,
|
| 1971 |
+
Doc(
|
| 1972 |
+
"""
|
| 1973 |
+
Default value if the parameter field is not set.
|
| 1974 |
+
"""
|
| 1975 |
+
),
|
| 1976 |
+
] = Undefined,
|
| 1977 |
+
*,
|
| 1978 |
+
default_factory: Annotated[
|
| 1979 |
+
Callable[[], Any] | None,
|
| 1980 |
+
Doc(
|
| 1981 |
+
"""
|
| 1982 |
+
A callable to generate the default value.
|
| 1983 |
+
|
| 1984 |
+
This doesn't affect `Path` parameters as the value is always required.
|
| 1985 |
+
The parameter is available only for compatibility.
|
| 1986 |
+
"""
|
| 1987 |
+
),
|
| 1988 |
+
] = _Unset,
|
| 1989 |
+
media_type: Annotated[
|
| 1990 |
+
str,
|
| 1991 |
+
Doc(
|
| 1992 |
+
"""
|
| 1993 |
+
The media type of this parameter field. Changing it would affect the
|
| 1994 |
+
generated OpenAPI, but currently it doesn't affect the parsing of the data.
|
| 1995 |
+
"""
|
| 1996 |
+
),
|
| 1997 |
+
] = "multipart/form-data",
|
| 1998 |
+
alias: Annotated[
|
| 1999 |
+
str | None,
|
| 2000 |
+
Doc(
|
| 2001 |
+
"""
|
| 2002 |
+
An alternative name for the parameter field.
|
| 2003 |
+
|
| 2004 |
+
This will be used to extract the data and for the generated OpenAPI.
|
| 2005 |
+
It is particularly useful when you can't use the name you want because it
|
| 2006 |
+
is a Python reserved keyword or similar.
|
| 2007 |
+
"""
|
| 2008 |
+
),
|
| 2009 |
+
] = None,
|
| 2010 |
+
alias_priority: Annotated[
|
| 2011 |
+
int | None,
|
| 2012 |
+
Doc(
|
| 2013 |
+
"""
|
| 2014 |
+
Priority of the alias. This affects whether an alias generator is used.
|
| 2015 |
+
"""
|
| 2016 |
+
),
|
| 2017 |
+
] = _Unset,
|
| 2018 |
+
validation_alias: Annotated[
|
| 2019 |
+
str | AliasPath | AliasChoices | None,
|
| 2020 |
+
Doc(
|
| 2021 |
+
"""
|
| 2022 |
+
'Whitelist' validation step. The parameter field will be the single one
|
| 2023 |
+
allowed by the alias or set of aliases defined.
|
| 2024 |
+
"""
|
| 2025 |
+
),
|
| 2026 |
+
] = None,
|
| 2027 |
+
serialization_alias: Annotated[
|
| 2028 |
+
str | None,
|
| 2029 |
+
Doc(
|
| 2030 |
+
"""
|
| 2031 |
+
'Blacklist' validation step. The vanilla parameter field will be the
|
| 2032 |
+
single one of the alias' or set of aliases' fields and all the other
|
| 2033 |
+
fields will be ignored at serialization time.
|
| 2034 |
+
"""
|
| 2035 |
+
),
|
| 2036 |
+
] = None,
|
| 2037 |
+
title: Annotated[
|
| 2038 |
+
str | None,
|
| 2039 |
+
Doc(
|
| 2040 |
+
"""
|
| 2041 |
+
Human-readable title.
|
| 2042 |
+
"""
|
| 2043 |
+
),
|
| 2044 |
+
] = None,
|
| 2045 |
+
description: Annotated[
|
| 2046 |
+
str | None,
|
| 2047 |
+
Doc(
|
| 2048 |
+
"""
|
| 2049 |
+
Human-readable description.
|
| 2050 |
+
"""
|
| 2051 |
+
),
|
| 2052 |
+
] = None,
|
| 2053 |
+
gt: Annotated[
|
| 2054 |
+
float | None,
|
| 2055 |
+
Doc(
|
| 2056 |
+
"""
|
| 2057 |
+
Greater than. If set, value must be greater than this. Only applicable to
|
| 2058 |
+
numbers.
|
| 2059 |
+
"""
|
| 2060 |
+
),
|
| 2061 |
+
] = None,
|
| 2062 |
+
ge: Annotated[
|
| 2063 |
+
float | None,
|
| 2064 |
+
Doc(
|
| 2065 |
+
"""
|
| 2066 |
+
Greater than or equal. If set, value must be greater than or equal to
|
| 2067 |
+
this. Only applicable to numbers.
|
| 2068 |
+
"""
|
| 2069 |
+
),
|
| 2070 |
+
] = None,
|
| 2071 |
+
lt: Annotated[
|
| 2072 |
+
float | None,
|
| 2073 |
+
Doc(
|
| 2074 |
+
"""
|
| 2075 |
+
Less than. If set, value must be less than this. Only applicable to numbers.
|
| 2076 |
+
"""
|
| 2077 |
+
),
|
| 2078 |
+
] = None,
|
| 2079 |
+
le: Annotated[
|
| 2080 |
+
float | None,
|
| 2081 |
+
Doc(
|
| 2082 |
+
"""
|
| 2083 |
+
Less than or equal. If set, value must be less than or equal to this.
|
| 2084 |
+
Only applicable to numbers.
|
| 2085 |
+
"""
|
| 2086 |
+
),
|
| 2087 |
+
] = None,
|
| 2088 |
+
min_length: Annotated[
|
| 2089 |
+
int | None,
|
| 2090 |
+
Doc(
|
| 2091 |
+
"""
|
| 2092 |
+
Minimum length for strings.
|
| 2093 |
+
"""
|
| 2094 |
+
),
|
| 2095 |
+
] = None,
|
| 2096 |
+
max_length: Annotated[
|
| 2097 |
+
int | None,
|
| 2098 |
+
Doc(
|
| 2099 |
+
"""
|
| 2100 |
+
Maximum length for strings.
|
| 2101 |
+
"""
|
| 2102 |
+
),
|
| 2103 |
+
] = None,
|
| 2104 |
+
pattern: Annotated[
|
| 2105 |
+
str | None,
|
| 2106 |
+
Doc(
|
| 2107 |
+
"""
|
| 2108 |
+
RegEx pattern for strings.
|
| 2109 |
+
"""
|
| 2110 |
+
),
|
| 2111 |
+
] = None,
|
| 2112 |
+
regex: Annotated[
|
| 2113 |
+
str | None,
|
| 2114 |
+
Doc(
|
| 2115 |
+
"""
|
| 2116 |
+
RegEx pattern for strings.
|
| 2117 |
+
"""
|
| 2118 |
+
),
|
| 2119 |
+
deprecated(
|
| 2120 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 2121 |
+
),
|
| 2122 |
+
] = None,
|
| 2123 |
+
discriminator: Annotated[
|
| 2124 |
+
str | None,
|
| 2125 |
+
Doc(
|
| 2126 |
+
"""
|
| 2127 |
+
Parameter field name for discriminating the type in a tagged union.
|
| 2128 |
+
"""
|
| 2129 |
+
),
|
| 2130 |
+
] = None,
|
| 2131 |
+
strict: Annotated[
|
| 2132 |
+
bool | None,
|
| 2133 |
+
Doc(
|
| 2134 |
+
"""
|
| 2135 |
+
If `True`, strict validation is applied to the field.
|
| 2136 |
+
"""
|
| 2137 |
+
),
|
| 2138 |
+
] = _Unset,
|
| 2139 |
+
multiple_of: Annotated[
|
| 2140 |
+
float | None,
|
| 2141 |
+
Doc(
|
| 2142 |
+
"""
|
| 2143 |
+
Value must be a multiple of this. Only applicable to numbers.
|
| 2144 |
+
"""
|
| 2145 |
+
),
|
| 2146 |
+
] = _Unset,
|
| 2147 |
+
allow_inf_nan: Annotated[
|
| 2148 |
+
bool | None,
|
| 2149 |
+
Doc(
|
| 2150 |
+
"""
|
| 2151 |
+
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
|
| 2152 |
+
"""
|
| 2153 |
+
),
|
| 2154 |
+
] = _Unset,
|
| 2155 |
+
max_digits: Annotated[
|
| 2156 |
+
int | None,
|
| 2157 |
+
Doc(
|
| 2158 |
+
"""
|
| 2159 |
+
Maximum number of digits allowed for decimal values.
|
| 2160 |
+
"""
|
| 2161 |
+
),
|
| 2162 |
+
] = _Unset,
|
| 2163 |
+
decimal_places: Annotated[
|
| 2164 |
+
int | None,
|
| 2165 |
+
Doc(
|
| 2166 |
+
"""
|
| 2167 |
+
Maximum number of decimal places allowed for decimal values.
|
| 2168 |
+
"""
|
| 2169 |
+
),
|
| 2170 |
+
] = _Unset,
|
| 2171 |
+
examples: Annotated[
|
| 2172 |
+
list[Any] | None,
|
| 2173 |
+
Doc(
|
| 2174 |
+
"""
|
| 2175 |
+
Example values for this field.
|
| 2176 |
+
|
| 2177 |
+
Read more about it in the
|
| 2178 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)
|
| 2179 |
+
"""
|
| 2180 |
+
),
|
| 2181 |
+
] = None,
|
| 2182 |
+
example: Annotated[
|
| 2183 |
+
Any | None,
|
| 2184 |
+
deprecated(
|
| 2185 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 2186 |
+
"although still supported. Use examples instead."
|
| 2187 |
+
),
|
| 2188 |
+
] = _Unset,
|
| 2189 |
+
openapi_examples: Annotated[
|
| 2190 |
+
dict[str, Example] | None,
|
| 2191 |
+
Doc(
|
| 2192 |
+
"""
|
| 2193 |
+
OpenAPI-specific examples.
|
| 2194 |
+
|
| 2195 |
+
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
|
| 2196 |
+
|
| 2197 |
+
Swagger UI (that provides the `/docs` interface) has better support for the
|
| 2198 |
+
OpenAPI-specific examples than the JSON Schema `examples`, that's the main
|
| 2199 |
+
use case for this.
|
| 2200 |
+
|
| 2201 |
+
Read more about it in the
|
| 2202 |
+
[FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).
|
| 2203 |
+
"""
|
| 2204 |
+
),
|
| 2205 |
+
] = None,
|
| 2206 |
+
deprecated: Annotated[
|
| 2207 |
+
deprecated | str | bool | None,
|
| 2208 |
+
Doc(
|
| 2209 |
+
"""
|
| 2210 |
+
Mark this parameter field as deprecated.
|
| 2211 |
+
|
| 2212 |
+
It will affect the generated OpenAPI (e.g. visible at `/docs`).
|
| 2213 |
+
"""
|
| 2214 |
+
),
|
| 2215 |
+
] = None,
|
| 2216 |
+
include_in_schema: Annotated[
|
| 2217 |
+
bool,
|
| 2218 |
+
Doc(
|
| 2219 |
+
"""
|
| 2220 |
+
To include (or not) this parameter field in the generated OpenAPI.
|
| 2221 |
+
You probably don't need it, but it's available.
|
| 2222 |
+
|
| 2223 |
+
This affects the generated OpenAPI (e.g. visible at `/docs`).
|
| 2224 |
+
"""
|
| 2225 |
+
),
|
| 2226 |
+
] = True,
|
| 2227 |
+
json_schema_extra: Annotated[
|
| 2228 |
+
dict[str, Any] | None,
|
| 2229 |
+
Doc(
|
| 2230 |
+
"""
|
| 2231 |
+
Any additional JSON schema data.
|
| 2232 |
+
"""
|
| 2233 |
+
),
|
| 2234 |
+
] = None,
|
| 2235 |
+
**extra: Annotated[
|
| 2236 |
+
Any,
|
| 2237 |
+
Doc(
|
| 2238 |
+
"""
|
| 2239 |
+
Include extra fields used by the JSON Schema.
|
| 2240 |
+
"""
|
| 2241 |
+
),
|
| 2242 |
+
deprecated(
|
| 2243 |
+
"""
|
| 2244 |
+
The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
|
| 2245 |
+
"""
|
| 2246 |
+
),
|
| 2247 |
+
],
|
| 2248 |
+
) -> Any:
|
| 2249 |
+
return params.File(
|
| 2250 |
+
default=default,
|
| 2251 |
+
default_factory=default_factory,
|
| 2252 |
+
media_type=media_type,
|
| 2253 |
+
alias=alias,
|
| 2254 |
+
alias_priority=alias_priority,
|
| 2255 |
+
validation_alias=validation_alias,
|
| 2256 |
+
serialization_alias=serialization_alias,
|
| 2257 |
+
title=title,
|
| 2258 |
+
description=description,
|
| 2259 |
+
gt=gt,
|
| 2260 |
+
ge=ge,
|
| 2261 |
+
lt=lt,
|
| 2262 |
+
le=le,
|
| 2263 |
+
min_length=min_length,
|
| 2264 |
+
max_length=max_length,
|
| 2265 |
+
pattern=pattern,
|
| 2266 |
+
regex=regex,
|
| 2267 |
+
discriminator=discriminator,
|
| 2268 |
+
strict=strict,
|
| 2269 |
+
multiple_of=multiple_of,
|
| 2270 |
+
allow_inf_nan=allow_inf_nan,
|
| 2271 |
+
max_digits=max_digits,
|
| 2272 |
+
decimal_places=decimal_places,
|
| 2273 |
+
example=example,
|
| 2274 |
+
examples=examples,
|
| 2275 |
+
openapi_examples=openapi_examples,
|
| 2276 |
+
deprecated=deprecated,
|
| 2277 |
+
include_in_schema=include_in_schema,
|
| 2278 |
+
json_schema_extra=json_schema_extra,
|
| 2279 |
+
**extra,
|
| 2280 |
+
)
|
| 2281 |
+
|
| 2282 |
+
|
| 2283 |
+
def Depends( # noqa: N802
|
| 2284 |
+
dependency: Annotated[
|
| 2285 |
+
Callable[..., Any] | None,
|
| 2286 |
+
Doc(
|
| 2287 |
+
"""
|
| 2288 |
+
A "dependable" callable (like a function).
|
| 2289 |
+
|
| 2290 |
+
Don't call it directly, FastAPI will call it for you, just pass the object
|
| 2291 |
+
directly.
|
| 2292 |
+
|
| 2293 |
+
Read more about it in the
|
| 2294 |
+
[FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)
|
| 2295 |
+
"""
|
| 2296 |
+
),
|
| 2297 |
+
] = None,
|
| 2298 |
+
*,
|
| 2299 |
+
use_cache: Annotated[
|
| 2300 |
+
bool,
|
| 2301 |
+
Doc(
|
| 2302 |
+
"""
|
| 2303 |
+
By default, after a dependency is called the first time in a request, if
|
| 2304 |
+
the dependency is declared again for the rest of the request (for example
|
| 2305 |
+
if the dependency is needed by several dependencies), the value will be
|
| 2306 |
+
re-used for the rest of the request.
|
| 2307 |
+
|
| 2308 |
+
Set `use_cache` to `False` to disable this behavior and ensure the
|
| 2309 |
+
dependency is called again (if declared more than once) in the same request.
|
| 2310 |
+
|
| 2311 |
+
Read more about it in the
|
| 2312 |
+
[FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)
|
| 2313 |
+
"""
|
| 2314 |
+
),
|
| 2315 |
+
] = True,
|
| 2316 |
+
scope: Annotated[
|
| 2317 |
+
Literal["function", "request"] | None,
|
| 2318 |
+
Doc(
|
| 2319 |
+
"""
|
| 2320 |
+
Mainly for dependencies with `yield`, define when the dependency function
|
| 2321 |
+
should start (the code before `yield`) and when it should end (the code
|
| 2322 |
+
after `yield`).
|
| 2323 |
+
|
| 2324 |
+
* `"function"`: start the dependency before the *path operation function*
|
| 2325 |
+
that handles the request, end the dependency after the *path operation
|
| 2326 |
+
function* ends, but **before** the response is sent back to the client.
|
| 2327 |
+
So, the dependency function will be executed **around** the *path operation
|
| 2328 |
+
**function***.
|
| 2329 |
+
* `"request"`: start the dependency before the *path operation function*
|
| 2330 |
+
that handles the request (similar to when using `"function"`), but end
|
| 2331 |
+
**after** the response is sent back to the client. So, the dependency
|
| 2332 |
+
function will be executed **around** the **request** and response cycle.
|
| 2333 |
+
|
| 2334 |
+
Read more about it in the
|
| 2335 |
+
[FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)
|
| 2336 |
+
"""
|
| 2337 |
+
),
|
| 2338 |
+
] = None,
|
| 2339 |
+
) -> Any:
|
| 2340 |
+
"""
|
| 2341 |
+
Declare a FastAPI dependency.
|
| 2342 |
+
|
| 2343 |
+
It takes a single "dependable" callable (like a function).
|
| 2344 |
+
|
| 2345 |
+
Don't call it directly, FastAPI will call it for you.
|
| 2346 |
+
|
| 2347 |
+
Read more about it in the
|
| 2348 |
+
[FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).
|
| 2349 |
+
|
| 2350 |
+
**Example**
|
| 2351 |
+
|
| 2352 |
+
```python
|
| 2353 |
+
from typing import Annotated
|
| 2354 |
+
|
| 2355 |
+
from fastapi import Depends, FastAPI
|
| 2356 |
+
|
| 2357 |
+
app = FastAPI()
|
| 2358 |
+
|
| 2359 |
+
|
| 2360 |
+
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
|
| 2361 |
+
return {"q": q, "skip": skip, "limit": limit}
|
| 2362 |
+
|
| 2363 |
+
|
| 2364 |
+
@app.get("/items/")
|
| 2365 |
+
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
|
| 2366 |
+
return commons
|
| 2367 |
+
```
|
| 2368 |
+
"""
|
| 2369 |
+
return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope)
|
| 2370 |
+
|
| 2371 |
+
|
| 2372 |
+
def Security( # noqa: N802
|
| 2373 |
+
dependency: Annotated[
|
| 2374 |
+
Callable[..., Any] | None,
|
| 2375 |
+
Doc(
|
| 2376 |
+
"""
|
| 2377 |
+
A "dependable" callable (like a function).
|
| 2378 |
+
|
| 2379 |
+
Don't call it directly, FastAPI will call it for you, just pass the object
|
| 2380 |
+
directly.
|
| 2381 |
+
|
| 2382 |
+
Read more about it in the
|
| 2383 |
+
[FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)
|
| 2384 |
+
"""
|
| 2385 |
+
),
|
| 2386 |
+
] = None,
|
| 2387 |
+
*,
|
| 2388 |
+
scopes: Annotated[
|
| 2389 |
+
Sequence[str] | None,
|
| 2390 |
+
Doc(
|
| 2391 |
+
"""
|
| 2392 |
+
OAuth2 scopes required for the *path operation* that uses this Security
|
| 2393 |
+
dependency.
|
| 2394 |
+
|
| 2395 |
+
The term "scope" comes from the OAuth2 specification, it seems to be
|
| 2396 |
+
intentionally vague and interpretable. It normally refers to permissions,
|
| 2397 |
+
in cases to roles.
|
| 2398 |
+
|
| 2399 |
+
These scopes are integrated with OpenAPI (and the API docs at `/docs`).
|
| 2400 |
+
So they are visible in the OpenAPI specification.
|
| 2401 |
+
|
| 2402 |
+
Read more about it in the
|
| 2403 |
+
[FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/)
|
| 2404 |
+
"""
|
| 2405 |
+
),
|
| 2406 |
+
] = None,
|
| 2407 |
+
use_cache: Annotated[
|
| 2408 |
+
bool,
|
| 2409 |
+
Doc(
|
| 2410 |
+
"""
|
| 2411 |
+
By default, after a dependency is called the first time in a request, if
|
| 2412 |
+
the dependency is declared again for the rest of the request (for example
|
| 2413 |
+
if the dependency is needed by several dependencies), the value will be
|
| 2414 |
+
re-used for the rest of the request.
|
| 2415 |
+
|
| 2416 |
+
Set `use_cache` to `False` to disable this behavior and ensure the
|
| 2417 |
+
dependency is called again (if declared more than once) in the same request.
|
| 2418 |
+
|
| 2419 |
+
Read more about it in the
|
| 2420 |
+
[FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)
|
| 2421 |
+
"""
|
| 2422 |
+
),
|
| 2423 |
+
] = True,
|
| 2424 |
+
) -> Any:
|
| 2425 |
+
"""
|
| 2426 |
+
Declare a FastAPI Security dependency.
|
| 2427 |
+
|
| 2428 |
+
The only difference with a regular dependency is that it can declare OAuth2
|
| 2429 |
+
scopes that will be integrated with OpenAPI and the automatic UI docs (by default
|
| 2430 |
+
at `/docs`).
|
| 2431 |
+
|
| 2432 |
+
It takes a single "dependable" callable (like a function).
|
| 2433 |
+
|
| 2434 |
+
Don't call it directly, FastAPI will call it for you.
|
| 2435 |
+
|
| 2436 |
+
Read more about it in the
|
| 2437 |
+
[FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and
|
| 2438 |
+
in the
|
| 2439 |
+
[FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
|
| 2440 |
+
|
| 2441 |
+
**Example**
|
| 2442 |
+
|
| 2443 |
+
```python
|
| 2444 |
+
from typing import Annotated
|
| 2445 |
+
|
| 2446 |
+
from fastapi import Security, FastAPI
|
| 2447 |
+
|
| 2448 |
+
from .db import User
|
| 2449 |
+
from .security import get_current_active_user
|
| 2450 |
+
|
| 2451 |
+
app = FastAPI()
|
| 2452 |
+
|
| 2453 |
+
@app.get("/users/me/items/")
|
| 2454 |
+
async def read_own_items(
|
| 2455 |
+
current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
|
| 2456 |
+
):
|
| 2457 |
+
return [{"item_id": "Foo", "owner": current_user.username}]
|
| 2458 |
+
```
|
| 2459 |
+
"""
|
| 2460 |
+
return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
|
lib/python3.11/site-packages/fastapi/params.py
ADDED
|
@@ -0,0 +1,754 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from collections.abc import Callable, Sequence
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from typing import Annotated, Any, Literal
|
| 6 |
+
|
| 7 |
+
from fastapi.exceptions import FastAPIDeprecationWarning
|
| 8 |
+
from fastapi.openapi.models import Example
|
| 9 |
+
from pydantic import AliasChoices, AliasPath
|
| 10 |
+
from pydantic.fields import FieldInfo
|
| 11 |
+
from typing_extensions import deprecated
|
| 12 |
+
|
| 13 |
+
from ._compat import (
|
| 14 |
+
Undefined,
|
| 15 |
+
)
|
| 16 |
+
from .datastructures import _Unset
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ParamTypes(Enum):
|
| 20 |
+
query = "query"
|
| 21 |
+
header = "header"
|
| 22 |
+
path = "path"
|
| 23 |
+
cookie = "cookie"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Param(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class]
|
| 27 |
+
in_: ParamTypes
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
default: Any = Undefined,
|
| 32 |
+
*,
|
| 33 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 34 |
+
annotation: Any | None = None,
|
| 35 |
+
alias: str | None = None,
|
| 36 |
+
alias_priority: int | None = _Unset,
|
| 37 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 38 |
+
serialization_alias: str | None = None,
|
| 39 |
+
title: str | None = None,
|
| 40 |
+
description: str | None = None,
|
| 41 |
+
gt: float | None = None,
|
| 42 |
+
ge: float | None = None,
|
| 43 |
+
lt: float | None = None,
|
| 44 |
+
le: float | None = None,
|
| 45 |
+
min_length: int | None = None,
|
| 46 |
+
max_length: int | None = None,
|
| 47 |
+
pattern: str | None = None,
|
| 48 |
+
regex: Annotated[
|
| 49 |
+
str | None,
|
| 50 |
+
deprecated(
|
| 51 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 52 |
+
),
|
| 53 |
+
] = None,
|
| 54 |
+
discriminator: str | None = None,
|
| 55 |
+
strict: bool | None = _Unset,
|
| 56 |
+
multiple_of: float | None = _Unset,
|
| 57 |
+
allow_inf_nan: bool | None = _Unset,
|
| 58 |
+
max_digits: int | None = _Unset,
|
| 59 |
+
decimal_places: int | None = _Unset,
|
| 60 |
+
examples: list[Any] | None = None,
|
| 61 |
+
example: Annotated[
|
| 62 |
+
Any | None,
|
| 63 |
+
deprecated(
|
| 64 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 65 |
+
"although still supported. Use examples instead."
|
| 66 |
+
),
|
| 67 |
+
] = _Unset,
|
| 68 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 69 |
+
deprecated: deprecated | str | bool | None = None,
|
| 70 |
+
include_in_schema: bool = True,
|
| 71 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 72 |
+
**extra: Any,
|
| 73 |
+
):
|
| 74 |
+
if example is not _Unset:
|
| 75 |
+
warnings.warn(
|
| 76 |
+
"`example` has been deprecated, please use `examples` instead",
|
| 77 |
+
category=FastAPIDeprecationWarning,
|
| 78 |
+
stacklevel=4,
|
| 79 |
+
)
|
| 80 |
+
self.example = example
|
| 81 |
+
self.include_in_schema = include_in_schema
|
| 82 |
+
self.openapi_examples = openapi_examples
|
| 83 |
+
kwargs = dict(
|
| 84 |
+
default=default,
|
| 85 |
+
default_factory=default_factory,
|
| 86 |
+
alias=alias,
|
| 87 |
+
title=title,
|
| 88 |
+
description=description,
|
| 89 |
+
gt=gt,
|
| 90 |
+
ge=ge,
|
| 91 |
+
lt=lt,
|
| 92 |
+
le=le,
|
| 93 |
+
min_length=min_length,
|
| 94 |
+
max_length=max_length,
|
| 95 |
+
discriminator=discriminator,
|
| 96 |
+
multiple_of=multiple_of,
|
| 97 |
+
allow_inf_nan=allow_inf_nan,
|
| 98 |
+
max_digits=max_digits,
|
| 99 |
+
decimal_places=decimal_places,
|
| 100 |
+
**extra,
|
| 101 |
+
)
|
| 102 |
+
if examples is not None:
|
| 103 |
+
kwargs["examples"] = examples
|
| 104 |
+
if regex is not None:
|
| 105 |
+
warnings.warn(
|
| 106 |
+
"`regex` has been deprecated, please use `pattern` instead",
|
| 107 |
+
category=FastAPIDeprecationWarning,
|
| 108 |
+
stacklevel=4,
|
| 109 |
+
)
|
| 110 |
+
current_json_schema_extra = json_schema_extra or extra
|
| 111 |
+
kwargs["deprecated"] = deprecated
|
| 112 |
+
|
| 113 |
+
if serialization_alias in (_Unset, None) and isinstance(alias, str):
|
| 114 |
+
serialization_alias = alias
|
| 115 |
+
if validation_alias in (_Unset, None):
|
| 116 |
+
validation_alias = alias
|
| 117 |
+
kwargs.update(
|
| 118 |
+
{
|
| 119 |
+
"annotation": annotation,
|
| 120 |
+
"alias_priority": alias_priority,
|
| 121 |
+
"validation_alias": validation_alias,
|
| 122 |
+
"serialization_alias": serialization_alias,
|
| 123 |
+
"strict": strict,
|
| 124 |
+
"json_schema_extra": current_json_schema_extra,
|
| 125 |
+
}
|
| 126 |
+
)
|
| 127 |
+
kwargs["pattern"] = pattern or regex
|
| 128 |
+
|
| 129 |
+
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
|
| 130 |
+
|
| 131 |
+
super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type]
|
| 132 |
+
|
| 133 |
+
def __repr__(self) -> str:
|
| 134 |
+
return f"{self.__class__.__name__}({self.default})"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class Path(Param): # type: ignore[misc]
|
| 138 |
+
in_ = ParamTypes.path
|
| 139 |
+
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
default: Any = ...,
|
| 143 |
+
*,
|
| 144 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 145 |
+
annotation: Any | None = None,
|
| 146 |
+
alias: str | None = None,
|
| 147 |
+
alias_priority: int | None = _Unset,
|
| 148 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 149 |
+
serialization_alias: str | None = None,
|
| 150 |
+
title: str | None = None,
|
| 151 |
+
description: str | None = None,
|
| 152 |
+
gt: float | None = None,
|
| 153 |
+
ge: float | None = None,
|
| 154 |
+
lt: float | None = None,
|
| 155 |
+
le: float | None = None,
|
| 156 |
+
min_length: int | None = None,
|
| 157 |
+
max_length: int | None = None,
|
| 158 |
+
pattern: str | None = None,
|
| 159 |
+
regex: Annotated[
|
| 160 |
+
str | None,
|
| 161 |
+
deprecated(
|
| 162 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 163 |
+
),
|
| 164 |
+
] = None,
|
| 165 |
+
discriminator: str | None = None,
|
| 166 |
+
strict: bool | None = _Unset,
|
| 167 |
+
multiple_of: float | None = _Unset,
|
| 168 |
+
allow_inf_nan: bool | None = _Unset,
|
| 169 |
+
max_digits: int | None = _Unset,
|
| 170 |
+
decimal_places: int | None = _Unset,
|
| 171 |
+
examples: list[Any] | None = None,
|
| 172 |
+
example: Annotated[
|
| 173 |
+
Any | None,
|
| 174 |
+
deprecated(
|
| 175 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 176 |
+
"although still supported. Use examples instead."
|
| 177 |
+
),
|
| 178 |
+
] = _Unset,
|
| 179 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 180 |
+
deprecated: deprecated | str | bool | None = None,
|
| 181 |
+
include_in_schema: bool = True,
|
| 182 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 183 |
+
**extra: Any,
|
| 184 |
+
):
|
| 185 |
+
assert default is ..., "Path parameters cannot have a default value"
|
| 186 |
+
self.in_ = self.in_
|
| 187 |
+
super().__init__(
|
| 188 |
+
default=default,
|
| 189 |
+
default_factory=default_factory,
|
| 190 |
+
annotation=annotation,
|
| 191 |
+
alias=alias,
|
| 192 |
+
alias_priority=alias_priority,
|
| 193 |
+
validation_alias=validation_alias,
|
| 194 |
+
serialization_alias=serialization_alias,
|
| 195 |
+
title=title,
|
| 196 |
+
description=description,
|
| 197 |
+
gt=gt,
|
| 198 |
+
ge=ge,
|
| 199 |
+
lt=lt,
|
| 200 |
+
le=le,
|
| 201 |
+
min_length=min_length,
|
| 202 |
+
max_length=max_length,
|
| 203 |
+
pattern=pattern,
|
| 204 |
+
regex=regex,
|
| 205 |
+
discriminator=discriminator,
|
| 206 |
+
strict=strict,
|
| 207 |
+
multiple_of=multiple_of,
|
| 208 |
+
allow_inf_nan=allow_inf_nan,
|
| 209 |
+
max_digits=max_digits,
|
| 210 |
+
decimal_places=decimal_places,
|
| 211 |
+
deprecated=deprecated,
|
| 212 |
+
example=example,
|
| 213 |
+
examples=examples,
|
| 214 |
+
openapi_examples=openapi_examples,
|
| 215 |
+
include_in_schema=include_in_schema,
|
| 216 |
+
json_schema_extra=json_schema_extra,
|
| 217 |
+
**extra,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class Query(Param): # type: ignore[misc]
|
| 222 |
+
in_ = ParamTypes.query
|
| 223 |
+
|
| 224 |
+
def __init__(
|
| 225 |
+
self,
|
| 226 |
+
default: Any = Undefined,
|
| 227 |
+
*,
|
| 228 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 229 |
+
annotation: Any | None = None,
|
| 230 |
+
alias: str | None = None,
|
| 231 |
+
alias_priority: int | None = _Unset,
|
| 232 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 233 |
+
serialization_alias: str | None = None,
|
| 234 |
+
title: str | None = None,
|
| 235 |
+
description: str | None = None,
|
| 236 |
+
gt: float | None = None,
|
| 237 |
+
ge: float | None = None,
|
| 238 |
+
lt: float | None = None,
|
| 239 |
+
le: float | None = None,
|
| 240 |
+
min_length: int | None = None,
|
| 241 |
+
max_length: int | None = None,
|
| 242 |
+
pattern: str | None = None,
|
| 243 |
+
regex: Annotated[
|
| 244 |
+
str | None,
|
| 245 |
+
deprecated(
|
| 246 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 247 |
+
),
|
| 248 |
+
] = None,
|
| 249 |
+
discriminator: str | None = None,
|
| 250 |
+
strict: bool | None = _Unset,
|
| 251 |
+
multiple_of: float | None = _Unset,
|
| 252 |
+
allow_inf_nan: bool | None = _Unset,
|
| 253 |
+
max_digits: int | None = _Unset,
|
| 254 |
+
decimal_places: int | None = _Unset,
|
| 255 |
+
examples: list[Any] | None = None,
|
| 256 |
+
example: Annotated[
|
| 257 |
+
Any | None,
|
| 258 |
+
deprecated(
|
| 259 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 260 |
+
"although still supported. Use examples instead."
|
| 261 |
+
),
|
| 262 |
+
] = _Unset,
|
| 263 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 264 |
+
deprecated: deprecated | str | bool | None = None,
|
| 265 |
+
include_in_schema: bool = True,
|
| 266 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 267 |
+
**extra: Any,
|
| 268 |
+
):
|
| 269 |
+
super().__init__(
|
| 270 |
+
default=default,
|
| 271 |
+
default_factory=default_factory,
|
| 272 |
+
annotation=annotation,
|
| 273 |
+
alias=alias,
|
| 274 |
+
alias_priority=alias_priority,
|
| 275 |
+
validation_alias=validation_alias,
|
| 276 |
+
serialization_alias=serialization_alias,
|
| 277 |
+
title=title,
|
| 278 |
+
description=description,
|
| 279 |
+
gt=gt,
|
| 280 |
+
ge=ge,
|
| 281 |
+
lt=lt,
|
| 282 |
+
le=le,
|
| 283 |
+
min_length=min_length,
|
| 284 |
+
max_length=max_length,
|
| 285 |
+
pattern=pattern,
|
| 286 |
+
regex=regex,
|
| 287 |
+
discriminator=discriminator,
|
| 288 |
+
strict=strict,
|
| 289 |
+
multiple_of=multiple_of,
|
| 290 |
+
allow_inf_nan=allow_inf_nan,
|
| 291 |
+
max_digits=max_digits,
|
| 292 |
+
decimal_places=decimal_places,
|
| 293 |
+
deprecated=deprecated,
|
| 294 |
+
example=example,
|
| 295 |
+
examples=examples,
|
| 296 |
+
openapi_examples=openapi_examples,
|
| 297 |
+
include_in_schema=include_in_schema,
|
| 298 |
+
json_schema_extra=json_schema_extra,
|
| 299 |
+
**extra,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class Header(Param): # type: ignore[misc]
|
| 304 |
+
in_ = ParamTypes.header
|
| 305 |
+
|
| 306 |
+
def __init__(
|
| 307 |
+
self,
|
| 308 |
+
default: Any = Undefined,
|
| 309 |
+
*,
|
| 310 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 311 |
+
annotation: Any | None = None,
|
| 312 |
+
alias: str | None = None,
|
| 313 |
+
alias_priority: int | None = _Unset,
|
| 314 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 315 |
+
serialization_alias: str | None = None,
|
| 316 |
+
convert_underscores: bool = True,
|
| 317 |
+
title: str | None = None,
|
| 318 |
+
description: str | None = None,
|
| 319 |
+
gt: float | None = None,
|
| 320 |
+
ge: float | None = None,
|
| 321 |
+
lt: float | None = None,
|
| 322 |
+
le: float | None = None,
|
| 323 |
+
min_length: int | None = None,
|
| 324 |
+
max_length: int | None = None,
|
| 325 |
+
pattern: str | None = None,
|
| 326 |
+
regex: Annotated[
|
| 327 |
+
str | None,
|
| 328 |
+
deprecated(
|
| 329 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 330 |
+
),
|
| 331 |
+
] = None,
|
| 332 |
+
discriminator: str | None = None,
|
| 333 |
+
strict: bool | None = _Unset,
|
| 334 |
+
multiple_of: float | None = _Unset,
|
| 335 |
+
allow_inf_nan: bool | None = _Unset,
|
| 336 |
+
max_digits: int | None = _Unset,
|
| 337 |
+
decimal_places: int | None = _Unset,
|
| 338 |
+
examples: list[Any] | None = None,
|
| 339 |
+
example: Annotated[
|
| 340 |
+
Any | None,
|
| 341 |
+
deprecated(
|
| 342 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 343 |
+
"although still supported. Use examples instead."
|
| 344 |
+
),
|
| 345 |
+
] = _Unset,
|
| 346 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 347 |
+
deprecated: deprecated | str | bool | None = None,
|
| 348 |
+
include_in_schema: bool = True,
|
| 349 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 350 |
+
**extra: Any,
|
| 351 |
+
):
|
| 352 |
+
self.convert_underscores = convert_underscores
|
| 353 |
+
super().__init__(
|
| 354 |
+
default=default,
|
| 355 |
+
default_factory=default_factory,
|
| 356 |
+
annotation=annotation,
|
| 357 |
+
alias=alias,
|
| 358 |
+
alias_priority=alias_priority,
|
| 359 |
+
validation_alias=validation_alias,
|
| 360 |
+
serialization_alias=serialization_alias,
|
| 361 |
+
title=title,
|
| 362 |
+
description=description,
|
| 363 |
+
gt=gt,
|
| 364 |
+
ge=ge,
|
| 365 |
+
lt=lt,
|
| 366 |
+
le=le,
|
| 367 |
+
min_length=min_length,
|
| 368 |
+
max_length=max_length,
|
| 369 |
+
pattern=pattern,
|
| 370 |
+
regex=regex,
|
| 371 |
+
discriminator=discriminator,
|
| 372 |
+
strict=strict,
|
| 373 |
+
multiple_of=multiple_of,
|
| 374 |
+
allow_inf_nan=allow_inf_nan,
|
| 375 |
+
max_digits=max_digits,
|
| 376 |
+
decimal_places=decimal_places,
|
| 377 |
+
deprecated=deprecated,
|
| 378 |
+
example=example,
|
| 379 |
+
examples=examples,
|
| 380 |
+
openapi_examples=openapi_examples,
|
| 381 |
+
include_in_schema=include_in_schema,
|
| 382 |
+
json_schema_extra=json_schema_extra,
|
| 383 |
+
**extra,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class Cookie(Param): # type: ignore[misc]
|
| 388 |
+
in_ = ParamTypes.cookie
|
| 389 |
+
|
| 390 |
+
def __init__(
|
| 391 |
+
self,
|
| 392 |
+
default: Any = Undefined,
|
| 393 |
+
*,
|
| 394 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 395 |
+
annotation: Any | None = None,
|
| 396 |
+
alias: str | None = None,
|
| 397 |
+
alias_priority: int | None = _Unset,
|
| 398 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 399 |
+
serialization_alias: str | None = None,
|
| 400 |
+
title: str | None = None,
|
| 401 |
+
description: str | None = None,
|
| 402 |
+
gt: float | None = None,
|
| 403 |
+
ge: float | None = None,
|
| 404 |
+
lt: float | None = None,
|
| 405 |
+
le: float | None = None,
|
| 406 |
+
min_length: int | None = None,
|
| 407 |
+
max_length: int | None = None,
|
| 408 |
+
pattern: str | None = None,
|
| 409 |
+
regex: Annotated[
|
| 410 |
+
str | None,
|
| 411 |
+
deprecated(
|
| 412 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 413 |
+
),
|
| 414 |
+
] = None,
|
| 415 |
+
discriminator: str | None = None,
|
| 416 |
+
strict: bool | None = _Unset,
|
| 417 |
+
multiple_of: float | None = _Unset,
|
| 418 |
+
allow_inf_nan: bool | None = _Unset,
|
| 419 |
+
max_digits: int | None = _Unset,
|
| 420 |
+
decimal_places: int | None = _Unset,
|
| 421 |
+
examples: list[Any] | None = None,
|
| 422 |
+
example: Annotated[
|
| 423 |
+
Any | None,
|
| 424 |
+
deprecated(
|
| 425 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 426 |
+
"although still supported. Use examples instead."
|
| 427 |
+
),
|
| 428 |
+
] = _Unset,
|
| 429 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 430 |
+
deprecated: deprecated | str | bool | None = None,
|
| 431 |
+
include_in_schema: bool = True,
|
| 432 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 433 |
+
**extra: Any,
|
| 434 |
+
):
|
| 435 |
+
super().__init__(
|
| 436 |
+
default=default,
|
| 437 |
+
default_factory=default_factory,
|
| 438 |
+
annotation=annotation,
|
| 439 |
+
alias=alias,
|
| 440 |
+
alias_priority=alias_priority,
|
| 441 |
+
validation_alias=validation_alias,
|
| 442 |
+
serialization_alias=serialization_alias,
|
| 443 |
+
title=title,
|
| 444 |
+
description=description,
|
| 445 |
+
gt=gt,
|
| 446 |
+
ge=ge,
|
| 447 |
+
lt=lt,
|
| 448 |
+
le=le,
|
| 449 |
+
min_length=min_length,
|
| 450 |
+
max_length=max_length,
|
| 451 |
+
pattern=pattern,
|
| 452 |
+
regex=regex,
|
| 453 |
+
discriminator=discriminator,
|
| 454 |
+
strict=strict,
|
| 455 |
+
multiple_of=multiple_of,
|
| 456 |
+
allow_inf_nan=allow_inf_nan,
|
| 457 |
+
max_digits=max_digits,
|
| 458 |
+
decimal_places=decimal_places,
|
| 459 |
+
deprecated=deprecated,
|
| 460 |
+
example=example,
|
| 461 |
+
examples=examples,
|
| 462 |
+
openapi_examples=openapi_examples,
|
| 463 |
+
include_in_schema=include_in_schema,
|
| 464 |
+
json_schema_extra=json_schema_extra,
|
| 465 |
+
**extra,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class Body(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class]
|
| 470 |
+
def __init__(
|
| 471 |
+
self,
|
| 472 |
+
default: Any = Undefined,
|
| 473 |
+
*,
|
| 474 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 475 |
+
annotation: Any | None = None,
|
| 476 |
+
embed: bool | None = None,
|
| 477 |
+
media_type: str = "application/json",
|
| 478 |
+
alias: str | None = None,
|
| 479 |
+
alias_priority: int | None = _Unset,
|
| 480 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 481 |
+
serialization_alias: str | None = None,
|
| 482 |
+
title: str | None = None,
|
| 483 |
+
description: str | None = None,
|
| 484 |
+
gt: float | None = None,
|
| 485 |
+
ge: float | None = None,
|
| 486 |
+
lt: float | None = None,
|
| 487 |
+
le: float | None = None,
|
| 488 |
+
min_length: int | None = None,
|
| 489 |
+
max_length: int | None = None,
|
| 490 |
+
pattern: str | None = None,
|
| 491 |
+
regex: Annotated[
|
| 492 |
+
str | None,
|
| 493 |
+
deprecated(
|
| 494 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 495 |
+
),
|
| 496 |
+
] = None,
|
| 497 |
+
discriminator: str | None = None,
|
| 498 |
+
strict: bool | None = _Unset,
|
| 499 |
+
multiple_of: float | None = _Unset,
|
| 500 |
+
allow_inf_nan: bool | None = _Unset,
|
| 501 |
+
max_digits: int | None = _Unset,
|
| 502 |
+
decimal_places: int | None = _Unset,
|
| 503 |
+
examples: list[Any] | None = None,
|
| 504 |
+
example: Annotated[
|
| 505 |
+
Any | None,
|
| 506 |
+
deprecated(
|
| 507 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 508 |
+
"although still supported. Use examples instead."
|
| 509 |
+
),
|
| 510 |
+
] = _Unset,
|
| 511 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 512 |
+
deprecated: deprecated | str | bool | None = None,
|
| 513 |
+
include_in_schema: bool = True,
|
| 514 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 515 |
+
**extra: Any,
|
| 516 |
+
):
|
| 517 |
+
self.embed = embed
|
| 518 |
+
self.media_type = media_type
|
| 519 |
+
if example is not _Unset:
|
| 520 |
+
warnings.warn(
|
| 521 |
+
"`example` has been deprecated, please use `examples` instead",
|
| 522 |
+
category=FastAPIDeprecationWarning,
|
| 523 |
+
stacklevel=4,
|
| 524 |
+
)
|
| 525 |
+
self.example = example
|
| 526 |
+
self.include_in_schema = include_in_schema
|
| 527 |
+
self.openapi_examples = openapi_examples
|
| 528 |
+
kwargs = dict(
|
| 529 |
+
default=default,
|
| 530 |
+
default_factory=default_factory,
|
| 531 |
+
alias=alias,
|
| 532 |
+
title=title,
|
| 533 |
+
description=description,
|
| 534 |
+
gt=gt,
|
| 535 |
+
ge=ge,
|
| 536 |
+
lt=lt,
|
| 537 |
+
le=le,
|
| 538 |
+
min_length=min_length,
|
| 539 |
+
max_length=max_length,
|
| 540 |
+
discriminator=discriminator,
|
| 541 |
+
multiple_of=multiple_of,
|
| 542 |
+
allow_inf_nan=allow_inf_nan,
|
| 543 |
+
max_digits=max_digits,
|
| 544 |
+
decimal_places=decimal_places,
|
| 545 |
+
**extra,
|
| 546 |
+
)
|
| 547 |
+
if examples is not None:
|
| 548 |
+
kwargs["examples"] = examples
|
| 549 |
+
if regex is not None:
|
| 550 |
+
warnings.warn(
|
| 551 |
+
"`regex` has been deprecated, please use `pattern` instead",
|
| 552 |
+
category=FastAPIDeprecationWarning,
|
| 553 |
+
stacklevel=4,
|
| 554 |
+
)
|
| 555 |
+
current_json_schema_extra = json_schema_extra or extra
|
| 556 |
+
kwargs["deprecated"] = deprecated
|
| 557 |
+
if serialization_alias in (_Unset, None) and isinstance(alias, str):
|
| 558 |
+
serialization_alias = alias
|
| 559 |
+
if validation_alias in (_Unset, None):
|
| 560 |
+
validation_alias = alias
|
| 561 |
+
kwargs.update(
|
| 562 |
+
{
|
| 563 |
+
"annotation": annotation,
|
| 564 |
+
"alias_priority": alias_priority,
|
| 565 |
+
"validation_alias": validation_alias,
|
| 566 |
+
"serialization_alias": serialization_alias,
|
| 567 |
+
"strict": strict,
|
| 568 |
+
"json_schema_extra": current_json_schema_extra,
|
| 569 |
+
}
|
| 570 |
+
)
|
| 571 |
+
kwargs["pattern"] = pattern or regex
|
| 572 |
+
|
| 573 |
+
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
|
| 574 |
+
|
| 575 |
+
super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type]
|
| 576 |
+
|
| 577 |
+
def __repr__(self) -> str:
|
| 578 |
+
return f"{self.__class__.__name__}({self.default})"
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
class Form(Body): # type: ignore[misc]
|
| 582 |
+
def __init__(
|
| 583 |
+
self,
|
| 584 |
+
default: Any = Undefined,
|
| 585 |
+
*,
|
| 586 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 587 |
+
annotation: Any | None = None,
|
| 588 |
+
media_type: str = "application/x-www-form-urlencoded",
|
| 589 |
+
alias: str | None = None,
|
| 590 |
+
alias_priority: int | None = _Unset,
|
| 591 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 592 |
+
serialization_alias: str | None = None,
|
| 593 |
+
title: str | None = None,
|
| 594 |
+
description: str | None = None,
|
| 595 |
+
gt: float | None = None,
|
| 596 |
+
ge: float | None = None,
|
| 597 |
+
lt: float | None = None,
|
| 598 |
+
le: float | None = None,
|
| 599 |
+
min_length: int | None = None,
|
| 600 |
+
max_length: int | None = None,
|
| 601 |
+
pattern: str | None = None,
|
| 602 |
+
regex: Annotated[
|
| 603 |
+
str | None,
|
| 604 |
+
deprecated(
|
| 605 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 606 |
+
),
|
| 607 |
+
] = None,
|
| 608 |
+
discriminator: str | None = None,
|
| 609 |
+
strict: bool | None = _Unset,
|
| 610 |
+
multiple_of: float | None = _Unset,
|
| 611 |
+
allow_inf_nan: bool | None = _Unset,
|
| 612 |
+
max_digits: int | None = _Unset,
|
| 613 |
+
decimal_places: int | None = _Unset,
|
| 614 |
+
examples: list[Any] | None = None,
|
| 615 |
+
example: Annotated[
|
| 616 |
+
Any | None,
|
| 617 |
+
deprecated(
|
| 618 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 619 |
+
"although still supported. Use examples instead."
|
| 620 |
+
),
|
| 621 |
+
] = _Unset,
|
| 622 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 623 |
+
deprecated: deprecated | str | bool | None = None,
|
| 624 |
+
include_in_schema: bool = True,
|
| 625 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 626 |
+
**extra: Any,
|
| 627 |
+
):
|
| 628 |
+
super().__init__(
|
| 629 |
+
default=default,
|
| 630 |
+
default_factory=default_factory,
|
| 631 |
+
annotation=annotation,
|
| 632 |
+
media_type=media_type,
|
| 633 |
+
alias=alias,
|
| 634 |
+
alias_priority=alias_priority,
|
| 635 |
+
validation_alias=validation_alias,
|
| 636 |
+
serialization_alias=serialization_alias,
|
| 637 |
+
title=title,
|
| 638 |
+
description=description,
|
| 639 |
+
gt=gt,
|
| 640 |
+
ge=ge,
|
| 641 |
+
lt=lt,
|
| 642 |
+
le=le,
|
| 643 |
+
min_length=min_length,
|
| 644 |
+
max_length=max_length,
|
| 645 |
+
pattern=pattern,
|
| 646 |
+
regex=regex,
|
| 647 |
+
discriminator=discriminator,
|
| 648 |
+
strict=strict,
|
| 649 |
+
multiple_of=multiple_of,
|
| 650 |
+
allow_inf_nan=allow_inf_nan,
|
| 651 |
+
max_digits=max_digits,
|
| 652 |
+
decimal_places=decimal_places,
|
| 653 |
+
deprecated=deprecated,
|
| 654 |
+
example=example,
|
| 655 |
+
examples=examples,
|
| 656 |
+
openapi_examples=openapi_examples,
|
| 657 |
+
include_in_schema=include_in_schema,
|
| 658 |
+
json_schema_extra=json_schema_extra,
|
| 659 |
+
**extra,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
class File(Form): # type: ignore[misc]
|
| 664 |
+
def __init__(
|
| 665 |
+
self,
|
| 666 |
+
default: Any = Undefined,
|
| 667 |
+
*,
|
| 668 |
+
default_factory: Callable[[], Any] | None = _Unset,
|
| 669 |
+
annotation: Any | None = None,
|
| 670 |
+
media_type: str = "multipart/form-data",
|
| 671 |
+
alias: str | None = None,
|
| 672 |
+
alias_priority: int | None = _Unset,
|
| 673 |
+
validation_alias: str | AliasPath | AliasChoices | None = None,
|
| 674 |
+
serialization_alias: str | None = None,
|
| 675 |
+
title: str | None = None,
|
| 676 |
+
description: str | None = None,
|
| 677 |
+
gt: float | None = None,
|
| 678 |
+
ge: float | None = None,
|
| 679 |
+
lt: float | None = None,
|
| 680 |
+
le: float | None = None,
|
| 681 |
+
min_length: int | None = None,
|
| 682 |
+
max_length: int | None = None,
|
| 683 |
+
pattern: str | None = None,
|
| 684 |
+
regex: Annotated[
|
| 685 |
+
str | None,
|
| 686 |
+
deprecated(
|
| 687 |
+
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
|
| 688 |
+
),
|
| 689 |
+
] = None,
|
| 690 |
+
discriminator: str | None = None,
|
| 691 |
+
strict: bool | None = _Unset,
|
| 692 |
+
multiple_of: float | None = _Unset,
|
| 693 |
+
allow_inf_nan: bool | None = _Unset,
|
| 694 |
+
max_digits: int | None = _Unset,
|
| 695 |
+
decimal_places: int | None = _Unset,
|
| 696 |
+
examples: list[Any] | None = None,
|
| 697 |
+
example: Annotated[
|
| 698 |
+
Any | None,
|
| 699 |
+
deprecated(
|
| 700 |
+
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
|
| 701 |
+
"although still supported. Use examples instead."
|
| 702 |
+
),
|
| 703 |
+
] = _Unset,
|
| 704 |
+
openapi_examples: dict[str, Example] | None = None,
|
| 705 |
+
deprecated: deprecated | str | bool | None = None,
|
| 706 |
+
include_in_schema: bool = True,
|
| 707 |
+
json_schema_extra: dict[str, Any] | None = None,
|
| 708 |
+
**extra: Any,
|
| 709 |
+
):
|
| 710 |
+
super().__init__(
|
| 711 |
+
default=default,
|
| 712 |
+
default_factory=default_factory,
|
| 713 |
+
annotation=annotation,
|
| 714 |
+
media_type=media_type,
|
| 715 |
+
alias=alias,
|
| 716 |
+
alias_priority=alias_priority,
|
| 717 |
+
validation_alias=validation_alias,
|
| 718 |
+
serialization_alias=serialization_alias,
|
| 719 |
+
title=title,
|
| 720 |
+
description=description,
|
| 721 |
+
gt=gt,
|
| 722 |
+
ge=ge,
|
| 723 |
+
lt=lt,
|
| 724 |
+
le=le,
|
| 725 |
+
min_length=min_length,
|
| 726 |
+
max_length=max_length,
|
| 727 |
+
pattern=pattern,
|
| 728 |
+
regex=regex,
|
| 729 |
+
discriminator=discriminator,
|
| 730 |
+
strict=strict,
|
| 731 |
+
multiple_of=multiple_of,
|
| 732 |
+
allow_inf_nan=allow_inf_nan,
|
| 733 |
+
max_digits=max_digits,
|
| 734 |
+
decimal_places=decimal_places,
|
| 735 |
+
deprecated=deprecated,
|
| 736 |
+
example=example,
|
| 737 |
+
examples=examples,
|
| 738 |
+
openapi_examples=openapi_examples,
|
| 739 |
+
include_in_schema=include_in_schema,
|
| 740 |
+
json_schema_extra=json_schema_extra,
|
| 741 |
+
**extra,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@dataclass(frozen=True)
|
| 746 |
+
class Depends:
|
| 747 |
+
dependency: Callable[..., Any] | None = None
|
| 748 |
+
use_cache: bool = True
|
| 749 |
+
scope: Literal["function", "request"] | None = None
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
@dataclass(frozen=True)
|
| 753 |
+
class Security(Depends):
|
| 754 |
+
scopes: Sequence[str] | None = None
|
lib/python3.11/site-packages/fastapi/py.typed
ADDED
|
File without changes
|
lib/python3.11/site-packages/fastapi/requests.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401
|
| 2 |
+
from starlette.requests import Request as Request # noqa: F401
|
lib/python3.11/site-packages/fastapi/responses.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
from typing import Any, Protocol, cast
|
| 3 |
+
|
| 4 |
+
from fastapi.exceptions import FastAPIDeprecationWarning
|
| 5 |
+
from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa
|
| 6 |
+
from starlette.responses import FileResponse as FileResponse # noqa
|
| 7 |
+
from starlette.responses import HTMLResponse as HTMLResponse # noqa
|
| 8 |
+
from starlette.responses import JSONResponse as JSONResponse # noqa
|
| 9 |
+
from starlette.responses import PlainTextResponse as PlainTextResponse # noqa
|
| 10 |
+
from starlette.responses import RedirectResponse as RedirectResponse # noqa
|
| 11 |
+
from starlette.responses import Response as Response # noqa
|
| 12 |
+
from starlette.responses import StreamingResponse as StreamingResponse # noqa
|
| 13 |
+
from typing_extensions import deprecated
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class _UjsonModule(Protocol):
|
| 17 |
+
def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ...
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class _OrjsonModule(Protocol):
|
| 21 |
+
OPT_NON_STR_KEYS: int
|
| 22 |
+
OPT_SERIALIZE_NUMPY: int
|
| 23 |
+
|
| 24 |
+
def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ...
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
ujson = cast(_UjsonModule, importlib.import_module("ujson"))
|
| 29 |
+
except ModuleNotFoundError: # pragma: nocover
|
| 30 |
+
ujson = None # type: ignore[assignment]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
orjson = cast(_OrjsonModule, importlib.import_module("orjson"))
|
| 35 |
+
except ModuleNotFoundError: # pragma: nocover
|
| 36 |
+
orjson = None # type: ignore[assignment]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@deprecated(
|
| 40 |
+
"UJSONResponse is deprecated, FastAPI now serializes data directly to JSON "
|
| 41 |
+
"bytes via Pydantic when a return type or response model is set, which is "
|
| 42 |
+
"faster and doesn't need a custom response class. Read more in the FastAPI "
|
| 43 |
+
"docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model "
|
| 44 |
+
"and https://fastapi.tiangolo.com/tutorial/response-model/",
|
| 45 |
+
category=FastAPIDeprecationWarning,
|
| 46 |
+
stacklevel=2,
|
| 47 |
+
)
|
| 48 |
+
class UJSONResponse(JSONResponse):
|
| 49 |
+
"""JSON response using the ujson library to serialize data to JSON.
|
| 50 |
+
|
| 51 |
+
**Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data
|
| 52 |
+
directly to JSON bytes via Pydantic when a return type or response model is
|
| 53 |
+
set, which is faster and doesn't need a custom response class.
|
| 54 |
+
|
| 55 |
+
Read more in the
|
| 56 |
+
[FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)
|
| 57 |
+
and the
|
| 58 |
+
[FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
|
| 59 |
+
|
| 60 |
+
**Note**: `ujson` is not included with FastAPI and must be installed
|
| 61 |
+
separately, e.g. `pip install ujson`.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def render(self, content: Any) -> bytes:
|
| 65 |
+
assert ujson is not None, "ujson must be installed to use UJSONResponse"
|
| 66 |
+
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@deprecated(
|
| 70 |
+
"ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON "
|
| 71 |
+
"bytes via Pydantic when a return type or response model is set, which is "
|
| 72 |
+
"faster and doesn't need a custom response class. Read more in the FastAPI "
|
| 73 |
+
"docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model "
|
| 74 |
+
"and https://fastapi.tiangolo.com/tutorial/response-model/",
|
| 75 |
+
category=FastAPIDeprecationWarning,
|
| 76 |
+
stacklevel=2,
|
| 77 |
+
)
|
| 78 |
+
class ORJSONResponse(JSONResponse):
|
| 79 |
+
"""JSON response using the orjson library to serialize data to JSON.
|
| 80 |
+
|
| 81 |
+
**Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data
|
| 82 |
+
directly to JSON bytes via Pydantic when a return type or response model is
|
| 83 |
+
set, which is faster and doesn't need a custom response class.
|
| 84 |
+
|
| 85 |
+
Read more in the
|
| 86 |
+
[FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)
|
| 87 |
+
and the
|
| 88 |
+
[FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
|
| 89 |
+
|
| 90 |
+
**Note**: `orjson` is not included with FastAPI and must be installed
|
| 91 |
+
separately, e.g. `pip install orjson`.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def render(self, content: Any) -> bytes:
|
| 95 |
+
assert orjson is not None, "orjson must be installed to use ORJSONResponse"
|
| 96 |
+
return orjson.dumps(
|
| 97 |
+
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
|
| 98 |
+
)
|
lib/python3.11/site-packages/fastapi/routing.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.11/site-packages/fastapi/sse.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Annotated, Any
|
| 2 |
+
|
| 3 |
+
from annotated_doc import Doc
|
| 4 |
+
from pydantic import AfterValidator, BaseModel, Field, model_validator
|
| 5 |
+
from starlette.responses import StreamingResponse
|
| 6 |
+
|
| 7 |
+
# Canonical SSE event schema matching the OpenAPI 3.2 spec
|
| 8 |
+
# (Section 4.14.4 "Special Considerations for Server-Sent Events")
|
| 9 |
+
_SSE_EVENT_SCHEMA: dict[str, Any] = {
|
| 10 |
+
"type": "object",
|
| 11 |
+
"properties": {
|
| 12 |
+
"data": {"type": "string"},
|
| 13 |
+
"event": {"type": "string"},
|
| 14 |
+
"id": {"type": "string"},
|
| 15 |
+
"retry": {"type": "integer", "minimum": 0},
|
| 16 |
+
},
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EventSourceResponse(StreamingResponse):
|
| 21 |
+
"""Streaming response with `text/event-stream` media type.
|
| 22 |
+
|
| 23 |
+
Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield`
|
| 24 |
+
to enable Server Sent Events (SSE) responses.
|
| 25 |
+
|
| 26 |
+
Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible
|
| 27 |
+
with protocols like MCP that stream SSE over `POST`.
|
| 28 |
+
|
| 29 |
+
The actual encoding logic lives in the FastAPI routing layer. This class
|
| 30 |
+
serves mainly as a marker and sets the correct `Content-Type`.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
media_type = "text/event-stream"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _check_single_line(v: str | None, field_name: str) -> str | None:
|
| 37 |
+
if v is not None and ("\r" in v or "\n" in v):
|
| 38 |
+
raise ValueError(f"SSE '{field_name}' must be a single line")
|
| 39 |
+
return v
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _check_event_single_line(v: str | None) -> str | None:
|
| 43 |
+
return _check_single_line(v, "event")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _check_id_valid(v: str | None) -> str | None:
|
| 47 |
+
if v is not None and "\0" in v:
|
| 48 |
+
raise ValueError("SSE 'id' must not contain null characters")
|
| 49 |
+
return _check_single_line(v, "id")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ServerSentEvent(BaseModel):
|
| 53 |
+
"""Represents a single Server-Sent Event.
|
| 54 |
+
|
| 55 |
+
When `yield`ed from a *path operation function* that uses
|
| 56 |
+
`response_class=EventSourceResponse`, each `ServerSentEvent` is encoded
|
| 57 |
+
into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream)
|
| 58 |
+
(`text/event-stream`).
|
| 59 |
+
|
| 60 |
+
If you yield a plain object (dict, Pydantic model, etc.) instead, it is
|
| 61 |
+
automatically JSON-encoded and sent as the `data:` field.
|
| 62 |
+
|
| 63 |
+
All `data` values **including plain strings** are JSON-serialized.
|
| 64 |
+
|
| 65 |
+
For example, `data="hello"` produces `data: "hello"` on the wire (with
|
| 66 |
+
quotes).
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
data: Annotated[
|
| 70 |
+
Any,
|
| 71 |
+
Doc(
|
| 72 |
+
"""
|
| 73 |
+
The event payload.
|
| 74 |
+
|
| 75 |
+
Can be any JSON-serializable value: a Pydantic model, dict, list,
|
| 76 |
+
string, number, etc. It is **always** serialized to JSON: strings
|
| 77 |
+
are quoted (`"hello"` becomes `data: "hello"` on the wire).
|
| 78 |
+
|
| 79 |
+
Mutually exclusive with `raw_data`.
|
| 80 |
+
"""
|
| 81 |
+
),
|
| 82 |
+
] = None
|
| 83 |
+
raw_data: Annotated[
|
| 84 |
+
str | None,
|
| 85 |
+
Doc(
|
| 86 |
+
"""
|
| 87 |
+
Raw string to send as the `data:` field **without** JSON encoding.
|
| 88 |
+
|
| 89 |
+
Use this when you need to send pre-formatted text, HTML fragments,
|
| 90 |
+
CSV lines, or any non-JSON payload. The string is placed directly
|
| 91 |
+
into the `data:` field as-is.
|
| 92 |
+
|
| 93 |
+
Mutually exclusive with `data`.
|
| 94 |
+
"""
|
| 95 |
+
),
|
| 96 |
+
] = None
|
| 97 |
+
event: Annotated[
|
| 98 |
+
str | None,
|
| 99 |
+
AfterValidator(_check_event_single_line),
|
| 100 |
+
Doc(
|
| 101 |
+
"""
|
| 102 |
+
Optional event type name.
|
| 103 |
+
|
| 104 |
+
Maps to `addEventListener(event, ...)` on the browser. When omitted,
|
| 105 |
+
the browser dispatches on the generic `message` event. Must be a
|
| 106 |
+
single line.
|
| 107 |
+
"""
|
| 108 |
+
),
|
| 109 |
+
] = None
|
| 110 |
+
id: Annotated[
|
| 111 |
+
str | None,
|
| 112 |
+
AfterValidator(_check_id_valid),
|
| 113 |
+
Doc(
|
| 114 |
+
"""
|
| 115 |
+
Optional event ID.
|
| 116 |
+
|
| 117 |
+
The browser sends this value back as the `Last-Event-ID` header on
|
| 118 |
+
automatic reconnection. **Must be a single line** and must not contain
|
| 119 |
+
null (`\\0`) characters.
|
| 120 |
+
"""
|
| 121 |
+
),
|
| 122 |
+
] = None
|
| 123 |
+
retry: Annotated[
|
| 124 |
+
int | None,
|
| 125 |
+
Field(ge=0),
|
| 126 |
+
Doc(
|
| 127 |
+
"""
|
| 128 |
+
Optional reconnection time in **milliseconds**.
|
| 129 |
+
|
| 130 |
+
Tells the browser how long to wait before reconnecting after the
|
| 131 |
+
connection is lost. Must be a non-negative integer.
|
| 132 |
+
"""
|
| 133 |
+
),
|
| 134 |
+
] = None
|
| 135 |
+
comment: Annotated[
|
| 136 |
+
str | None,
|
| 137 |
+
Doc(
|
| 138 |
+
"""
|
| 139 |
+
Optional comment line(s).
|
| 140 |
+
|
| 141 |
+
Comment lines start with `:` in the SSE wire format and are ignored by
|
| 142 |
+
`EventSource` clients. Useful for keep-alive pings to prevent
|
| 143 |
+
proxy/load-balancer timeouts.
|
| 144 |
+
"""
|
| 145 |
+
),
|
| 146 |
+
] = None
|
| 147 |
+
|
| 148 |
+
@model_validator(mode="after")
|
| 149 |
+
def _check_data_exclusive(self) -> "ServerSentEvent":
|
| 150 |
+
if self.data is not None and self.raw_data is not None:
|
| 151 |
+
raise ValueError(
|
| 152 |
+
"Cannot set both 'data' and 'raw_data' on the same "
|
| 153 |
+
"ServerSentEvent. Use 'data' for JSON-serialized payloads "
|
| 154 |
+
"or 'raw_data' for pre-formatted strings."
|
| 155 |
+
)
|
| 156 |
+
return self
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def format_sse_event(
|
| 160 |
+
*,
|
| 161 |
+
data_str: Annotated[
|
| 162 |
+
str | None,
|
| 163 |
+
Doc(
|
| 164 |
+
"""
|
| 165 |
+
Pre-serialized data string to use as the `data:` field.
|
| 166 |
+
"""
|
| 167 |
+
),
|
| 168 |
+
] = None,
|
| 169 |
+
event: Annotated[
|
| 170 |
+
str | None,
|
| 171 |
+
Doc(
|
| 172 |
+
"""
|
| 173 |
+
Optional event type name (`event:` field).
|
| 174 |
+
"""
|
| 175 |
+
),
|
| 176 |
+
] = None,
|
| 177 |
+
id: Annotated[
|
| 178 |
+
str | None,
|
| 179 |
+
Doc(
|
| 180 |
+
"""
|
| 181 |
+
Optional event ID (`id:` field).
|
| 182 |
+
"""
|
| 183 |
+
),
|
| 184 |
+
] = None,
|
| 185 |
+
retry: Annotated[
|
| 186 |
+
int | None,
|
| 187 |
+
Doc(
|
| 188 |
+
"""
|
| 189 |
+
Optional reconnection time in milliseconds (`retry:` field).
|
| 190 |
+
"""
|
| 191 |
+
),
|
| 192 |
+
] = None,
|
| 193 |
+
comment: Annotated[
|
| 194 |
+
str | None,
|
| 195 |
+
Doc(
|
| 196 |
+
"""
|
| 197 |
+
Optional comment line(s) (`:` prefix).
|
| 198 |
+
"""
|
| 199 |
+
),
|
| 200 |
+
] = None,
|
| 201 |
+
) -> bytes:
|
| 202 |
+
"""Build SSE wire-format bytes from **pre-serialized** data.
|
| 203 |
+
|
| 204 |
+
The result always ends with `\n\n` (the event terminator).
|
| 205 |
+
"""
|
| 206 |
+
lines: list[str] = []
|
| 207 |
+
|
| 208 |
+
if comment is not None:
|
| 209 |
+
for line in comment.splitlines():
|
| 210 |
+
lines.append(f": {line}")
|
| 211 |
+
|
| 212 |
+
if event is not None:
|
| 213 |
+
lines.append(f"event: {event}")
|
| 214 |
+
|
| 215 |
+
if data_str is not None:
|
| 216 |
+
for line in data_str.splitlines():
|
| 217 |
+
lines.append(f"data: {line}")
|
| 218 |
+
|
| 219 |
+
if id is not None:
|
| 220 |
+
lines.append(f"id: {id}")
|
| 221 |
+
|
| 222 |
+
if retry is not None:
|
| 223 |
+
lines.append(f"retry: {retry}")
|
| 224 |
+
|
| 225 |
+
lines.append("")
|
| 226 |
+
lines.append("")
|
| 227 |
+
return "\n".join(lines).encode("utf-8")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# Keep-alive comment, per the SSE spec recommendation
|
| 231 |
+
KEEPALIVE_COMMENT = b": ping\n\n"
|
| 232 |
+
|
| 233 |
+
# Seconds between keep-alive pings when a generator is idle.
|
| 234 |
+
# Private but importable so tests can monkeypatch it.
|
| 235 |
+
_PING_INTERVAL: float = 15.0
|
lib/python3.11/site-packages/fastapi/staticfiles.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.staticfiles import StaticFiles as StaticFiles # noqa
|
lib/python3.11/site-packages/fastapi/templating.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.templating import Jinja2Templates as Jinja2Templates # noqa
|
lib/python3.11/site-packages/fastapi/testclient.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from starlette.testclient import TestClient as TestClient # noqa
|
lib/python3.11/site-packages/fastapi/types.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import types
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from enum import Enum
|
| 4 |
+
from typing import Any, TypeVar, Union
|
| 5 |
+
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
from pydantic.main import IncEx as IncEx
|
| 8 |
+
|
| 9 |
+
DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any])
|
| 10 |
+
UnionType = getattr(types, "UnionType", Union)
|
| 11 |
+
ModelNameMap = dict[type[BaseModel] | type[Enum], str]
|
| 12 |
+
DependencyCacheKey = tuple[Callable[..., Any] | None, tuple[str, ...], str]
|
lib/python3.11/site-packages/fastapi/utils.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import warnings
|
| 3 |
+
from typing import (
|
| 4 |
+
TYPE_CHECKING,
|
| 5 |
+
Any,
|
| 6 |
+
Literal,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
import fastapi
|
| 10 |
+
from fastapi._compat import (
|
| 11 |
+
ModelField,
|
| 12 |
+
PydanticSchemaGenerationError,
|
| 13 |
+
Undefined,
|
| 14 |
+
annotation_is_pydantic_v1,
|
| 15 |
+
)
|
| 16 |
+
from fastapi.datastructures import DefaultPlaceholder, DefaultType
|
| 17 |
+
from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError
|
| 18 |
+
from pydantic.fields import FieldInfo
|
| 19 |
+
|
| 20 |
+
from ._compat import v2
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING: # pragma: nocover
|
| 23 |
+
from .routing import APIRoute
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def is_body_allowed_for_status_code(status_code: int | str | None) -> bool:
|
| 27 |
+
if status_code is None:
|
| 28 |
+
return True
|
| 29 |
+
# Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1
|
| 30 |
+
if status_code in {
|
| 31 |
+
"default",
|
| 32 |
+
"1XX",
|
| 33 |
+
"2XX",
|
| 34 |
+
"3XX",
|
| 35 |
+
"4XX",
|
| 36 |
+
"5XX",
|
| 37 |
+
}:
|
| 38 |
+
return True
|
| 39 |
+
current_status_code = int(status_code)
|
| 40 |
+
return not (current_status_code < 200 or current_status_code in {204, 205, 304})
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_path_param_names(path: str) -> set[str]:
|
| 44 |
+
return set(re.findall("{(.*?)}", path))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
_invalid_args_message = (
|
| 48 |
+
"Invalid args for response field! Hint: "
|
| 49 |
+
"check that {type_} is a valid Pydantic field type. "
|
| 50 |
+
"If you are using a return type annotation that is not a valid Pydantic "
|
| 51 |
+
"field (e.g. Union[Response, dict, None]) you can disable generating the "
|
| 52 |
+
"response model from the type annotation with the path operation decorator "
|
| 53 |
+
"parameter response_model=None. Read more: "
|
| 54 |
+
"https://fastapi.tiangolo.com/tutorial/response-model/"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def create_model_field(
|
| 59 |
+
name: str,
|
| 60 |
+
type_: Any,
|
| 61 |
+
default: Any | None = Undefined,
|
| 62 |
+
field_info: FieldInfo | None = None,
|
| 63 |
+
alias: str | None = None,
|
| 64 |
+
mode: Literal["validation", "serialization"] = "validation",
|
| 65 |
+
) -> ModelField:
|
| 66 |
+
if annotation_is_pydantic_v1(type_):
|
| 67 |
+
raise PydanticV1NotSupportedError(
|
| 68 |
+
"pydantic.v1 models are no longer supported by FastAPI."
|
| 69 |
+
f" Please update the response model {type_!r}."
|
| 70 |
+
)
|
| 71 |
+
field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias)
|
| 72 |
+
try:
|
| 73 |
+
return v2.ModelField(mode=mode, name=name, field_info=field_info)
|
| 74 |
+
except PydanticSchemaGenerationError:
|
| 75 |
+
raise fastapi.exceptions.FastAPIError(
|
| 76 |
+
_invalid_args_message.format(type_=type_)
|
| 77 |
+
) from None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def generate_operation_id_for_path(
|
| 81 |
+
*, name: str, path: str, method: str
|
| 82 |
+
) -> str: # pragma: nocover
|
| 83 |
+
warnings.warn(
|
| 84 |
+
message="fastapi.utils.generate_operation_id_for_path() was deprecated, "
|
| 85 |
+
"it is not used internally, and will be removed soon",
|
| 86 |
+
category=FastAPIDeprecationWarning,
|
| 87 |
+
stacklevel=2,
|
| 88 |
+
)
|
| 89 |
+
operation_id = f"{name}{path}"
|
| 90 |
+
operation_id = re.sub(r"\W", "_", operation_id)
|
| 91 |
+
operation_id = f"{operation_id}_{method.lower()}"
|
| 92 |
+
return operation_id
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def generate_unique_id(route: "APIRoute") -> str:
|
| 96 |
+
operation_id = f"{route.name}{route.path_format}"
|
| 97 |
+
operation_id = re.sub(r"\W", "_", operation_id)
|
| 98 |
+
assert route.methods
|
| 99 |
+
operation_id = f"{operation_id}_{list(route.methods)[0].lower()}"
|
| 100 |
+
return operation_id
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None:
|
| 104 |
+
for key, value in update_dict.items():
|
| 105 |
+
if (
|
| 106 |
+
key in main_dict
|
| 107 |
+
and isinstance(main_dict[key], dict)
|
| 108 |
+
and isinstance(value, dict)
|
| 109 |
+
):
|
| 110 |
+
deep_dict_update(main_dict[key], value)
|
| 111 |
+
elif (
|
| 112 |
+
key in main_dict
|
| 113 |
+
and isinstance(main_dict[key], list)
|
| 114 |
+
and isinstance(update_dict[key], list)
|
| 115 |
+
):
|
| 116 |
+
main_dict[key] = main_dict[key] + update_dict[key]
|
| 117 |
+
else:
|
| 118 |
+
main_dict[key] = value
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_value_or_default(
|
| 122 |
+
first_item: DefaultPlaceholder | DefaultType,
|
| 123 |
+
*extra_items: DefaultPlaceholder | DefaultType,
|
| 124 |
+
) -> DefaultPlaceholder | DefaultType:
|
| 125 |
+
"""
|
| 126 |
+
Pass items or `DefaultPlaceholder`s by descending priority.
|
| 127 |
+
|
| 128 |
+
The first one to _not_ be a `DefaultPlaceholder` will be returned.
|
| 129 |
+
|
| 130 |
+
Otherwise, the first item (a `DefaultPlaceholder`) will be returned.
|
| 131 |
+
"""
|
| 132 |
+
items = (first_item,) + extra_items
|
| 133 |
+
for item in items:
|
| 134 |
+
if not isinstance(item, DefaultPlaceholder):
|
| 135 |
+
return item
|
| 136 |
+
return first_item
|