Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/METADATAAdded+187
- lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/RECORDAdded+11
- lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/WHEELAdded+4
- lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/licenses/LICENSEAdded+32
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/METADATAAdded+169
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/RECORDAdded+101
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/REQUESTEDAdded
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/WHEELAdded+5
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/licenses/LICENSEAdded+201
- lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/top_level.txtAdded+1
- lib/python3.12/site-packages/fastapi/__init__.pyAdded+25
- lib/python3.12/site-packages/fastapi/__main__.pyAdded+3
- lib/python3.12/site-packages/fastapi/__pycache__/param_functions.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/_compat.pyAdded+659
- lib/python3.12/site-packages/fastapi/applications.pyAdded
- lib/python3.12/site-packages/fastapi/background.pyAdded+59
- lib/python3.12/site-packages/fastapi/cli.pyAdded+13
- lib/python3.12/site-packages/fastapi/concurrency.pyAdded+39
- lib/python3.12/site-packages/fastapi/datastructures.pyAdded+204
- lib/python3.12/site-packages/fastapi/encoders.pyAdded+343
- lib/python3.12/site-packages/fastapi/exception_handlers.pyAdded+34
- lib/python3.12/site-packages/fastapi/exceptions.pyAdded+176
- lib/python3.12/site-packages/fastapi/logger.pyAdded+3
- lib/python3.12/site-packages/fastapi/openapi/__init__.pyAdded
- lib/python3.12/site-packages/fastapi/openapi/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/openapi/__pycache__/constants.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/openapi/__pycache__/docs.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/openapi/__pycache__/models.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/openapi/__pycache__/utils.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/openapi/constants.pyAdded+3
- lib/python3.12/site-packages/fastapi/openapi/docs.pyAdded+344
- lib/python3.12/site-packages/fastapi/openapi/models.pyAdded+445
- lib/python3.12/site-packages/fastapi/openapi/utils.pyAdded+569
- lib/python3.12/site-packages/fastapi/param_functions.pyAdded+2360
- lib/python3.12/site-packages/fastapi/params.pyAdded+786
- lib/python3.12/site-packages/fastapi/py.typedAdded
- lib/python3.12/site-packages/fastapi/requests.pyAdded+2
- lib/python3.12/site-packages/fastapi/responses.pyAdded+48
- lib/python3.12/site-packages/fastapi/routing.pyAdded
- lib/python3.12/site-packages/fastapi/security/__init__.pyAdded+15
- lib/python3.12/site-packages/fastapi/security/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/api_key.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/base.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/http.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/oauth2.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/open_id_connect_url.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/__pycache__/utils.cpython-312.pycAdded
- lib/python3.12/site-packages/fastapi/security/api_key.pyAdded+288
1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187Metadata-Version: 2.4Name: cloudpickleVersion: 3.1.2Summary: Pickler class to extend the standard pickle.Pickler functionalityHome-page: https://github.com/cloudpipe/cloudpickleAuthor: The cloudpickle developer teamAuthor-email: cloudpipe@googlegroups.comRequires-Python: >=3.8Description-Content-Type: text/markdownLicense: BSD-3-ClauseClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: BSD LicenseClassifier: Operating System :: POSIXClassifier: Operating System :: Microsoft :: WindowsClassifier: Operating System :: MacOS :: MacOS XClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Scientific/EngineeringClassifier: Topic :: System :: Distributed ComputingLicense-File: LICENSE
# cloudpickle
[](https://github.com/cloudpipe/cloudpickle/actions)[](https://codecov.io/github/cloudpipe/cloudpickle?branch=master)
`cloudpickle` makes it possible to serialize Python constructs not supportedby the default `pickle` module from the Python standard library.
`cloudpickle` is especially useful for **cluster computing** where Pythoncode is shipped over the network to execute on remote hosts, possibly closeto the data.
Among other things, `cloudpickle` supports pickling for **lambda functions**along with **functions and classes defined interactively** in the`__main__` module (for instance in a script, a shell or a Jupyter notebook).
Cloudpickle can only be used to send objects between the **exact same versionof Python**.
Using `cloudpickle` for **long-term object storage is not supported andstrongly discouraged.**
**Security notice**: one should **only load pickle data from trusted sources** asotherwise `pickle.load` can lead to arbitrary code execution resulting in a criticalsecurity vulnerability.
Installation------------
The latest release of `cloudpickle` is available from[pypi](https://pypi.python.org/pypi/cloudpickle):
pip install cloudpickle
Examples--------
Pickling a lambda expression:
```python>>> import cloudpickle>>> squared = lambda x: x ** 2>>> pickled_lambda = cloudpickle.dumps(squared)
>>> import pickle>>> new_squared = pickle.loads(pickled_lambda)>>> new_squared(2)4```
Pickling a function interactively defined in a Python shell session(in the `__main__` module):
```python>>> CONSTANT = 42>>> def my_function(data: int) -> int:... return data + CONSTANT...>>> pickled_function = cloudpickle.dumps(my_function)>>> depickled_function = pickle.loads(pickled_function)>>> depickled_function<function __main__.my_function(data:int) -> int>>>> depickled_function(43)85```
Overriding pickle's serialization mechanism for importable constructs:----------------------------------------------------------------------
An important difference between `cloudpickle` and `pickle` is that`cloudpickle` can serialize a function or class **by value**, whereas `pickle`can only serialize it **by reference**. Serialization by reference treatsfunctions and classes as attributes of modules, and pickles them throughinstructions that trigger the import of their module at load time.Serialization by reference is thus limited in that it assumes that the modulecontaining the function or class is available/importable in the unpicklingenvironment. This assumption breaks when pickling constructs defined in aninteractive session, a case that is automatically detected by `cloudpickle`,that pickles such constructs **by value**.
Another case where the importability assumption is expected to break is whendeveloping a module in a distributed execution environment: the workerprocesses may not have access to the said module, for example if they live on adifferent machine than the process in which the module is being developed. Byitself, `cloudpickle` cannot detect such "locally importable" modules andswitch to serialization by value; instead, it relies on its default mode, whichis serialization by reference. However, since `cloudpickle 2.0.0`, one canexplicitly specify modules for which serialization by value should be used,using the`register_pickle_by_value(module)`/`/unregister_pickle_by_value(module)` API:
```python>>> import cloudpickle>>> import my_module>>> cloudpickle.register_pickle_by_value(my_module)>>> cloudpickle.dumps(my_module.my_function) # my_function is pickled by value>>> cloudpickle.unregister_pickle_by_value(my_module)>>> cloudpickle.dumps(my_module.my_function) # my_function is pickled by reference```
Using this API, there is no need to re-install the new version of the module onall the worker nodes nor to restart the workers: restarting the client Pythonprocess with the new source code is enough.
Note that this feature is still **experimental**, and may fail in the followingsituations:
- If the body of a function/class pickled by value contains an `import` statement: ```python >>> def f(): >>> ... from another_module import g >>> ... # calling f in the unpickling environment may fail if another_module >>> ... # is unavailable >>> ... return g() + 1 ```
- If a function pickled by reference uses a function pickled by value during its execution.
Running the tests-----------------
- With `tox`, to test run the tests for all the supported versions of Python and PyPy:
pip install tox tox
or alternatively for a specific environment:
tox -e py312
- With `pytest` to only run the tests for your current version of Python:
pip install -r dev-requirements.txt PYTHONPATH='.:tests' pytest
History-------
`cloudpickle` was initially developed by [picloud.com](http://web.archive.org/web/20140721022102/http://blog.picloud.com/2013/11/17/picloud-has-joined-dropbox/) and shipped as part ofthe client SDK.
A copy of `cloudpickle.py` was included as part of PySpark, the Pythoninterface to [Apache Spark](https://spark.apache.org/). Davies Liu, JoshRosen, Thom Neale and other Apache Spark developers improved it significantly,most notably to add support for PyPy and Python 3.
The aim of the `cloudpickle` project is to make that work available to a wideraudience outside of the Spark ecosystem and to make it easier to improve itfurther notably with the help of a dedicated non-regression test suite.
1234567891011cloudpickle-3.1.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
cloudpickle-3.1.2.dist-info/METADATA,sha256=PQJjv-nuTyOyRL3K_3OsvnoZV-v4J0O2rkJpOtxI1yE,7079
cloudpickle-3.1.2.dist-info/RECORD,,
cloudpickle-3.1.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
cloudpickle-3.1.2.dist-info/licenses/LICENSE,sha256=MCnqNBc-n9wjOtMV3GsQC9HqcfUpscGvl2ZKJy_cVfU,1754
cloudpickle/__init__.py,sha256=ErKyvqqAErOkbCowrizhGpN9DN-TaD22QtqI9CQ9sDw,308
cloudpickle/__pycache__/__init__.cpython-312.pyc,,
cloudpickle/__pycache__/cloudpickle.cpython-312.pyc,,
cloudpickle/__pycache__/cloudpickle_fast.cpython-312.pyc,,
cloudpickle/cloudpickle.py,sha256=KcLA_uAxp2KuMJb9vaTVve7FLFUQu7mYkD3dCscxeRc,58874
cloudpickle/cloudpickle_fast.py,sha256=AI5ZKf2AbLNxD8lXyLDpKZyzeZ2ofFtdK1ZWFq_ec1c,3231234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any1234567891011121314151617181920212223242526272829303132This module was extracted from the `cloud` package, developed byPiCloud, Inc.
Copyright (c) 2015, Cloudpickle contributors.Copyright (c) 2012, Regents of the University of California.Copyright (c) 2009 PiCloud, Inc. http://www.picloud.com.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169Metadata-Version: 2.4Name: compressed-tensorsVersion: 0.9.3Summary: Library for utilization of compressed safetensors of neural network modelsHome-page: https://github.com/neuralmagic/compressed-tensorsAuthor: Neuralmagic, Inc.Author-email: support@neuralmagic.comLicense: Apache 2.0Description-Content-Type: text/markdownLicense-File: LICENSERequires-Dist: torch>=1.7.0Requires-Dist: transformersRequires-Dist: pydantic>=2.0Provides-Extra: devRequires-Dist: black==22.12.0; extra == "dev"Requires-Dist: isort==5.8.0; extra == "dev"Requires-Dist: wheel>=0.36.2; extra == "dev"Requires-Dist: flake8>=3.8.3; extra == "dev"Requires-Dist: pytest>=6.0.0; extra == "dev"Requires-Dist: nbconvert>=7.16.3; extra == "dev"Provides-Extra: accelerateRequires-Dist: accelerate; extra == "accelerate"Dynamic: authorDynamic: author-emailDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: provides-extraDynamic: requires-distDynamic: summary
# compressed-tensors
The `compressed-tensors` library extends the [safetensors](https://github.com/huggingface/safetensors) format, providing a versatile and efficient way to store and manage compressed tensor data. This library supports various quantization and sparsity schemes, making it a unified format for handling different model optimizations like GPTQ, AWQ, SmoothQuant, INT8, FP8, SparseGPT, and more.
## Why `compressed-tensors`?
As model compression becomes increasingly important for efficient deployment of LLMs, the landscape of quantization and compression techniques has become increasingly fragmented.Each method often comes with its own storage format and loading procedures, making it challenging to work with multiple techniques or switch between them.`compressed-tensors` addresses this by providing a single, extensible format that can represent a wide variety of compression schemes.
* **Unified Checkpoint Format**: Supports various compression schemes in a single, consistent format.* **Wide Compatibility**: Works with popular quantization methods like GPTQ, SmoothQuant, and FP8. See [llm-compressor](https://github.com/vllm-project/llm-compressor)* **Flexible Quantization Support**: * Weight-only quantization (e.g., W4A16, W8A16, WnA16) * Activation quantization (e.g., W8A8) * KV cache quantization * Non-uniform schemes (different layers can be quantized in different ways!)* **Sparsity Support**: Handles both unstructured and semi-structured (e.g., 2:4) sparsity patterns.* **Open-Source Integration**: Designed to work seamlessly with Hugging Face models and PyTorch.
This allows developers and researchers to easily experiment with composing different quantization methods, simplify model deployment pipelines, and reduce the overhead of supporting multiple compression formats in inference engines.
## Installation
### From [PyPI](https://pypi.org/project/compressed-tensors)
Stable release:```bashpip install compressed-tensors```
Nightly release:```bashpip install compressed-tensors-nightly```
### From Source
```bashgit clone https://github.com/neuralmagic/compressed-tensorscd compressed-tensorspip install -e .```
## Getting started
### Saving/Loading Compressed Tensors (Bitmask Compression)
The function `save_compressed` uses the `compression_format` argument to apply compression to tensors.The function `load_compressed` reverses the process: converts the compressed weights on disk to decompressed weights in device memory.
```pythonfrom compressed_tensors import save_compressed, load_compressed, BitmaskConfigfrom torch import Tensorfrom typing import Dict
# the example BitmaskConfig method efficiently compresses # tensors with large number of zero entries compression_config = BitmaskConfig()
tensors: Dict[str, Tensor] = {"tensor_1": Tensor( [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])}# compress tensors using BitmaskConfig compression format (save them efficiently on disk)save_compressed(tensors, "model.safetensors", compression_format=compression_config.format)
# decompress tensors (load_compressed returns a generator for memory efficiency)decompressed_tensors = {}for tensor_name, tensor in load_compressed("model.safetensors", compression_config = compression_config): decompressed_tensors[tensor_name] = tensor```
## Saving/Loading Compressed Models (Bitmask Compression)
We can apply bitmask compression to a whole model. For more detailed example see `example` directory.```pythonfrom compressed_tensors import save_compressed_model, load_compressed, BitmaskConfigfrom transformers import AutoModelForCausalLM
model_name = "neuralmagic/llama2.c-stories110M-pruned50"model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
original_state_dict = model.state_dict()
compression_config = BitmaskConfig()
# save compressed model weightssave_compressed_model(model, "compressed_model.safetensors", compression_format=compression_config.format)
# load compressed model weights (`dict` turns generator into a dictionary)state_dict = dict(load_compressed("compressed_model.safetensors", compression_config))```
For more in-depth tutorial on bitmask compression, refer to the [notebook](https://github.com/neuralmagic/compressed-tensors/blob/d707c5b84bc3fef164aebdcd97cb6eaa571982f8/examples/bitmask_compression.ipynb).
## Saving a Compressed Model with PTQ
We can use compressed-tensors to run basic post training quantization (PTQ) and save the quantized model compressed on disk
```pythonmodel_name = "TinyLlama/TinyLlama-1.1B-intermediate-step-1431k-3T"model = AutoModelForCausalLM.from_pretrained(model_name, device_map="cuda:0", torch_dtype="auto")
config = QuantizationConfig.parse_file("./examples/bit_packing/int4_config.json")config.quantization_status = QuantizationStatus.CALIBRATIONapply_quantization_config(model, config)
dataset = load_dataset("ptb_text_only")["train"]tokenizer = AutoTokenizer.from_pretrained(model_name)
def tokenize_function(examples): return tokenizer(examples["sentence"], padding=False, truncation=True, max_length=1024)
tokenized_dataset = dataset.map(tokenize_function, batched=True)data_loader = DataLoader(tokenized_dataset, batch_size=1, collate_fn=DefaultDataCollator())
with torch.no_grad(): for idx, sample in tqdm(enumerate(data_loader), desc="Running calibration"): sample = {key: value.to(device) for key,value in sample.items()} _ = model(**sample)
if idx >= 512: break
model.apply(freeze_module_quantization)model.apply(compress_quantized_weights)
output_dir = "./ex_llama1.1b_w4a16_packed_quantize"compressor = ModelCompressor(quantization_config=config)compressed_state_dict = compressor.compress(model)model.save_pretrained(output_dir, state_dict=compressed_state_dict)```
For more in-depth tutorial on quantization compression, refer to the [notebook](./examples/quantize_and_pack_int4.ipynb).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101compressed_tensors-0.9.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
compressed_tensors-0.9.3.dist-info/METADATA,sha256=zs3aFaG-BGV9hqJbW9Zwzex0TVcM5sPZhiaeVx2qjR0,6997
compressed_tensors-0.9.3.dist-info/RECORD,,
compressed_tensors-0.9.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
compressed_tensors-0.9.3.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
compressed_tensors-0.9.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
compressed_tensors-0.9.3.dist-info/top_level.txt,sha256=w2i-GyPs2s1UwVxvutSvN_lM22SXC2hQFBmoMcPnV7Y,19
compressed_tensors/__init__.py,sha256=UtKmifNeBCSE2TZSAfduVNNzHY-3V7bLjZ7n7RuXLOE,812
compressed_tensors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/__pycache__/base.cpython-312.pyc,,
compressed_tensors/__pycache__/version.cpython-312.pyc,,
compressed_tensors/base.py,sha256=73HYH7HY7O2roC89yG_piPFnZwrBfn_i7HmKl90SKc0,875
compressed_tensors/compressors/__init__.py,sha256=smSygTSfcfuujRrAXDc6uZm4L_ccV1tWZewqVnOb4lM,825
compressed_tensors/compressors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/compressors/__pycache__/base.cpython-312.pyc,,
compressed_tensors/compressors/__pycache__/helpers.cpython-312.pyc,,
compressed_tensors/compressors/base.py,sha256=x8dQrWVEurynXw03yHJZTaAmrRTOsdZJoHjmvs0IKwk,7002
compressed_tensors/compressors/helpers.py,sha256=OK6qxX9j3bHwF9JfIYSGMgBJe2PWjlTA3byXKCJaTIQ,5431
compressed_tensors/compressors/model_compressors/__init__.py,sha256=5RGGPFu4YqEt_aOdFSQYFYFDjcZFJN0CsMqRtDZz3Js,666
compressed_tensors/compressors/model_compressors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/compressors/model_compressors/__pycache__/model_compressor.cpython-312.pyc,,
compressed_tensors/compressors/model_compressors/model_compressor.py,sha256=n0gcrKwefJuO6b4LNjCynJQf7NNqNHDcoLlzZgTCPGc,23080
compressed_tensors/compressors/quantized_compressors/__init__.py,sha256=09UJq68Pht6Bf-4iP9xYl3tetKsncNPHD8IAGbePsr4,714
compressed_tensors/compressors/quantized_compressors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/compressors/quantized_compressors/__pycache__/base.cpython-312.pyc,,
compressed_tensors/compressors/quantized_compressors/__pycache__/naive_quantized.cpython-312.pyc,,
compressed_tensors/compressors/quantized_compressors/__pycache__/pack_quantized.cpython-312.pyc,,
compressed_tensors/compressors/quantized_compressors/base.py,sha256=GXTSWgFAhksbno94Ulpth9-YM4a7NsDlx4oQGGB0swQ,8567
compressed_tensors/compressors/quantized_compressors/naive_quantized.py,sha256=fd0KlkSx6bvZ3xwIkK3jEUdPSUPs56Eua4dEDOtzKW0,5150
compressed_tensors/compressors/quantized_compressors/pack_quantized.py,sha256=zH2PocRe_T5yt1-3kLdZH9AUQWQyaVOi4U9nEJiYaWA,8509
compressed_tensors/compressors/sparse_compressors/__init__.py,sha256=Atuz-OdEgn8OCUhx7Ovd6gXdyImAI186uCR-uR0t_Nk,737
compressed_tensors/compressors/sparse_compressors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/compressors/sparse_compressors/__pycache__/base.cpython-312.pyc,,
compressed_tensors/compressors/sparse_compressors/__pycache__/dense.cpython-312.pyc,,
compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_24_bitmask.cpython-312.pyc,,
compressed_tensors/compressors/sparse_compressors/__pycache__/sparse_bitmask.cpython-312.pyc,,
compressed_tensors/compressors/sparse_compressors/base.py,sha256=CVWbs3sd7GKJEoWOIKImABQ01VOTX8dlF2AQaEVPotw,5883
compressed_tensors/compressors/sparse_compressors/dense.py,sha256=_uW_HISeDNz4yboSZWoh6GwrkUE6HFibzPQSKrHOCkg,1505
compressed_tensors/compressors/sparse_compressors/sparse_24_bitmask.py,sha256=mEKSSgpXookqYSJw3mlyP6cYYKD-eaIvpQMvi4JO6TY,8807
compressed_tensors/compressors/sparse_compressors/sparse_bitmask.py,sha256=S8vW0FI9ep_XtUQOxj0P5utJt3vKEYOHjWEPp-Xd9aY,5820
compressed_tensors/compressors/sparse_quantized_compressors/__init__.py,sha256=4f_cwcKXB1nVVMoiKgTFAc8jAPjPLElo-Df_EDm1_xw,675
compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/compressors/sparse_quantized_compressors/__pycache__/marlin_24.cpython-312.pyc,,
compressed_tensors/compressors/sparse_quantized_compressors/marlin_24.py,sha256=xY0CdHXAzVHeDeSCD_I-5UZKcntKzd3FiKSP-ZqcSBs,9614
compressed_tensors/config/__init__.py,sha256=8sOoZ6xvYSC79mBvEtO8l6xk4PC80d29AnnJiGMrY2M,737
compressed_tensors/config/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/config/__pycache__/base.cpython-312.pyc,,
compressed_tensors/config/__pycache__/dense.cpython-312.pyc,,
compressed_tensors/config/__pycache__/sparse_24_bitmask.cpython-312.pyc,,
compressed_tensors/config/__pycache__/sparse_bitmask.cpython-312.pyc,,
compressed_tensors/config/base.py,sha256=R3iUmFf1MslEjin5LgwQbmfJHIsS7Uw0UIxfn780uqY,3479
compressed_tensors/config/dense.py,sha256=NgSxnFCnckU9-iunxEaqiFwqgdO7YYxlWKR74jNbjks,1317
compressed_tensors/config/sparse_24_bitmask.py,sha256=Lhj39zT2V1hxftprvxvneyhv45ShlXOKd75DBbDTyTE,1401
compressed_tensors/config/sparse_bitmask.py,sha256=pZUboRNZTu6NajGOQEFExoPknak5ynVAUeiiYpS1Gt8,1308
compressed_tensors/linear/__init__.py,sha256=fH6rjBYAxuwrTzBTlTjTgCYNyh6TCvCqajCz4Im4YrA,617
compressed_tensors/linear/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/linear/__pycache__/compressed_linear.cpython-312.pyc,,
compressed_tensors/linear/compressed_linear.py,sha256=_m6XpNcI53eeSHO8VdiuAM6UBTdpDhn5Ivd8iRMwEKc,3980
compressed_tensors/quantization/__init__.py,sha256=83J5bPB7PavN2TfCoW7_vEDhfYpm4TDrqYO9vdSQ5bk,760
compressed_tensors/quantization/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/quantization/__pycache__/quant_args.cpython-312.pyc,,
compressed_tensors/quantization/__pycache__/quant_config.cpython-312.pyc,,
compressed_tensors/quantization/__pycache__/quant_scheme.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__init__.py,sha256=_uItzFWusyV74Zco_pHLOTdE9a83cL-R-ZdyQrBkIyw,772
compressed_tensors/quantization/lifecycle/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__pycache__/apply.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__pycache__/compressed.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__pycache__/forward.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__pycache__/helpers.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/__pycache__/initialize.cpython-312.pyc,,
compressed_tensors/quantization/lifecycle/apply.py,sha256=lZmCCSm1_o79iUAy460w6Bv9FaOvntVisMdS-dN9fnk,16594
compressed_tensors/quantization/lifecycle/compressed.py,sha256=Fj9n66IN0EWsOAkBHg3O0GlOQpxstqjCcs0ttzMXrJ0,2296
compressed_tensors/quantization/lifecycle/forward.py,sha256=DOWouUqfaLA4Qhg-ojVVBdhhSAlgZqFC26vZARxE0ko,12961
compressed_tensors/quantization/lifecycle/helpers.py,sha256=C0mhy2vJ0fCjVeN4kFNhw8Eq1wkteBGHiZ36RVLThRY,944
compressed_tensors/quantization/lifecycle/initialize.py,sha256=sK3PLm69N91QepBuq-83Qd2Br6XcOmRDpD5qo_WWNJo,7469
compressed_tensors/quantization/quant_args.py,sha256=sKpb8DcNObidjXjNol1Tn_Iih3ZXBycSp-fyz68TGhY,9117
compressed_tensors/quantization/quant_config.py,sha256=vx06wBo91p4LCb3Vzd-2eCTUeIf_Sz2ZXRP263eQyjQ,10385
compressed_tensors/quantization/quant_scheme.py,sha256=eQ0JrRZ80GX69fpwW87VzPzzhajhk4mUaJScjk82OY4,6010
compressed_tensors/quantization/utils/__init__.py,sha256=VdtEmP0bvuND_IGQnyqUPc5lnFp-1_yD7StKSX4x80w,656
compressed_tensors/quantization/utils/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/quantization/utils/__pycache__/helpers.cpython-312.pyc,,
compressed_tensors/quantization/utils/helpers.py,sha256=DBP-sGRpGAY01K0LFE7qqonNj4hkTYL_mXrMs2LtAD8,14100
compressed_tensors/registry/__init__.py,sha256=FwLSNYqfIrb5JD_6OK_MT4_svvKTN_nEhpgQlQvGbjI,658
compressed_tensors/registry/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/registry/__pycache__/registry.cpython-312.pyc,,
compressed_tensors/registry/registry.py,sha256=vRcjVB1ITfSbfYUaGndBBmqhip_5vsS62weorVg0iXo,11896
compressed_tensors/utils/__init__.py,sha256=gS4gSU2pwcAbsKj-6YMaqhm25udFy6ISYaWBf-myRSM,808
compressed_tensors/utils/__pycache__/__init__.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/helpers.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/offload.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/permutations_24.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/permute.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/safetensors_load.cpython-312.pyc,,
compressed_tensors/utils/__pycache__/semi_structured_conversions.cpython-312.pyc,,
compressed_tensors/utils/helpers.py,sha256=RrNvzD08naEjEiXdU-FdZjQVda1nQywu1hA_GCDj0vg,10415
compressed_tensors/utils/offload.py,sha256=H4aAg21zUvJM2uwE6QCNYazX_p_o41yQUAgLLWBqR0w,14079
compressed_tensors/utils/permutations_24.py,sha256=kx6fsfDHebx94zsSzhXGyCyuC9sVyah6BUUir_StT28,2530
compressed_tensors/utils/permute.py,sha256=V6tJLKo3Syccj-viv4F7ZKZgJeCB-hl-dK8RKI_kBwI,2355
compressed_tensors/utils/safetensors_load.py,sha256=5SeM2hzLh77Ne8Vk7qR6-km7cf8bhov41ExpWITqX3A,11470
compressed_tensors/utils/semi_structured_conversions.py,sha256=XKNffPum54kPASgqKzgKvyeqWPAkair2XEQXjkp7ho8,13489
compressed_tensors/version.py,sha256=X4y5lqlF1QFUgl25iumzagpg3dzyVoLP6i82HZEhCJA,158512345Wheel-Version: 1.0Generator: setuptools (78.1.0)Root-Is-Purelib: trueTag: py3-none-any
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1compressed_tensors12345678910111213141516171819202122232425"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.115.12"
from starlette import status as status
from .applications import FastAPI as FastAPIfrom .background import BackgroundTasks as BackgroundTasksfrom .datastructures import UploadFile as UploadFilefrom .exceptions import HTTPException as HTTPExceptionfrom .exceptions import WebSocketException as WebSocketExceptionfrom .param_functions import Body as Bodyfrom .param_functions import Cookie as Cookiefrom .param_functions import Depends as Dependsfrom .param_functions import File as Filefrom .param_functions import Form as Formfrom .param_functions import Header as Headerfrom .param_functions import Path as Pathfrom .param_functions import Query as Queryfrom .param_functions import Security as Securityfrom .requests import Request as Requestfrom .responses import Response as Responsefrom .routing import APIRouter as APIRouterfrom .websockets import WebSocket as WebSocketfrom .websockets import WebSocketDisconnect as WebSocketDisconnect123from fastapi.cli import main
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659from collections import dequefrom copy import copyfrom dataclasses import dataclass, is_dataclassfrom enum import Enumfrom functools import lru_cachefrom typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union,)
from fastapi.exceptions import RequestErrorModelfrom fastapi.types import IncEx, ModelNameMap, UnionTypefrom pydantic import BaseModel, create_modelfrom pydantic.version import VERSION as PYDANTIC_VERSIONfrom starlette.datastructures import UploadFilefrom typing_extensions import Annotated, Literal, get_args, get_origin
PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2])PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2
sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque,}
sequence_types = tuple(sequence_annotation_to_type.keys())
Url: Type[Any]
if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter from pydantic import ValidationError as ValidationError from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] GetJsonSchemaHandler as GetJsonSchemaHandler, ) from pydantic._internal._typing_extra import eval_type_lenient from pydantic._internal._utils import lenient_issubclass as lenient_issubclass from pydantic.fields import FieldInfo from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue from pydantic_core import CoreSchema as CoreSchema from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url
try: from pydantic_core.core_schema import ( with_info_plain_validator_function as with_info_plain_validator_function, ) except ImportError: # pragma: no cover from pydantic_core.core_schema import ( general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 )
RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any
class BaseConfig: pass
class ErrorWrapper(Exception): pass
@dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation"
@property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name
@property def required(self) -> bool: return self.field_info.is_required()
@property def default(self) -> Any: return self.get_default()
@property def type_(self) -> Any: return self.field_info.annotation
def __post_init__(self) -> None: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] )
def get_default(self) -> Any: if self.field_info.is_required(): return Undefined return self.field_info.get_default(call_default_factory=True)
def validate( self, value: Any, values: Dict[str, Any] = {}, # noqa: B006 *, loc: Tuple[Union[int, str], ...] = (), ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]: try: return ( self._type_adapter.validate_python(value, from_attributes=True), None, ) except ValidationError as exc: return None, _regenerate_error_with_loc( errors=exc.errors(include_url=False), loc_prefix=loc )
def serialize( self, value: Any, *, mode: Literal["json", "python"] = "json", include: Union[IncEx, None] = None, exclude: Union[IncEx, None] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: # What calls this code passes a value that already called # self._type_adapter.validate_python(value) return self._type_adapter.dump_python( value, mode=mode, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, )
def __hash__(self) -> int: # Each ModelField is unique for our purposes, to allow making a dict from # ModelField to its JSON Schema. return id(self)
def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation
def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value]
def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild()
def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs)
def _get_model_config(model: BaseModel) -> Any: return model.model_config
def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, override_mode or field.mode)] if "$ref" not in json_schema: # TODO remove when deprecating Pydantic v1 # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 json_schema["title"] = ( field.field_info.title or field.alias.title().replace("_", " ") ) return json_schema
def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {}
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value]
def is_scalar_field(field: ModelField) -> bool: from fastapi import params
return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body)
def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation)
def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation)
def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_)
def is_bytes_sequence_field(field: ModelField) -> bool: return is_bytes_sequence_annotation(field.type_)
def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: cls = type(field_info) merged_field_info = cls.from_annotation(annotation) new_field_info = copy(field_info) new_field_info.metadata = merged_field_info.metadata new_field_info.annotation = merged_field_info.annotation return new_field_info
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = ( get_origin(field.field_info.annotation) or field.field_info.annotation ) assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return]
def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors(include_url=False)[0] error["input"] = None return error # type: ignore[return-value]
def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel
def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return [ ModelField(field_info=field_info, name=name) for name, field_info in model.model_fields.items() ]
else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 )
# Keeping old "Required" functionality from Pydantic V1, without # shadowing typing.Required. RequiredParam: Any = Ellipsis # type: ignore[no-redef] from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 )
GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc]
sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, }
@dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str
class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass
def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {}
def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions
def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params
field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True
def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] for sub_field in field.sub_fields: # type: ignore[attr-defined] if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False
def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors
def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs()
def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs)
def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined]
def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0]
def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return]
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map )
def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field)
def is_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined]
def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field)
def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes)
def is_bytes_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined]
def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info)
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined]
def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value]
def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel
def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return list(model.__fields__.values()) # type: ignore[attr-defined]
def _regenerate_error_with_loc( *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]) -> List[Dict[str, Any]]: updated_loc_errors: List[Any] = [ {**err, "loc": loc_prefix + err.get("loc", ())} for err in _normalize_errors(errors) ]
return updated_loc_errors
def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: if lenient_issubclass(annotation, (str, bytes)): return False return lenient_issubclass(annotation, sequence_types)
def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if field_annotation_is_sequence(arg): return True return False return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) )
def value_is_sequence(value: Any) -> bool: return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type]
def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: return ( lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) or _annotation_is_sequence(annotation) or is_dataclass(annotation) )
def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: return any(field_annotation_is_complex(arg) for arg in get_args(annotation))
return ( _annotation_is_complex(annotation) or _annotation_is_complex(origin) or hasattr(origin, "__pydantic_core_schema__") or hasattr(origin, "__get_pydantic_core_schema__") )
def field_annotation_is_scalar(annotation: Any) -> bool: # handle Ellipsis here to make tuple[int, ...] work nicely return annotation is Ellipsis or not field_annotation_is_complex(annotation)
def field_annotation_is_scalar_sequence(annotation: Union[Type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one_scalar_sequence = False for arg in get_args(annotation): if field_annotation_is_scalar_sequence(arg): at_least_one_scalar_sequence = True continue elif not field_annotation_is_scalar(arg): return False return at_least_one_scalar_sequence return field_annotation_is_sequence(annotation) and all( field_annotation_is_scalar(sub_annotation) for sub_annotation in get_args(annotation) )
def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: if lenient_issubclass(annotation, bytes): return True origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if lenient_issubclass(arg, bytes): return True return False
def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: if lenient_issubclass(annotation, UploadFile): return True origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if lenient_issubclass(arg, UploadFile): return True return False
def is_bytes_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_bytes_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annotation_is_sequence(annotation) and all( is_bytes_or_nonable_bytes_annotation(sub_annotation) for sub_annotation in get_args(annotation) )
def is_uploadfile_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_uploadfile_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annotation_is_sequence(annotation) and all( is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) for sub_annotation in get_args(annotation) )
@lru_cachedef get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]: return get_model_fields(model)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859from typing import Any, Callable
from starlette.background import BackgroundTasks as StarletteBackgroundTasksfrom typing_extensions import Annotated, Doc, ParamSpec
P = ParamSpec("P")
class BackgroundTasks(StarletteBackgroundTasks): """ A collection of background tasks that will be called after a response has been sent to the client.
Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
## Example
```python from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content)
@app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"} ``` """
def add_task( self, func: Annotated[ Callable[P, Any], Doc( """ The function to call after the response is sent.
It can be a regular `def` function or an `async def` function. """ ), ], *args: P.args, **kwargs: P.kwargs, ) -> None: """ Add a function to be called in the background after the response is sent.
Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). """ return super().add_task(func, *args, **kwargs)12345678910111213try: from fastapi_cli.cli import main as cli_main
except ImportError: # pragma: no cover cli_main = None # type: ignore
def main() -> None: if not cli_main: # type: ignore[truthy-function] message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' print(message) raise RuntimeError(message) # noqa: B904 cli_main()123456789101112131415161718192021222324252627282930313233343536373839from contextlib import asynccontextmanager as asynccontextmanagerfrom typing import AsyncGenerator, ContextManager, TypeVar
import anyio.to_threadfrom anyio import CapacityLimiterfrom starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqafrom starlette.concurrency import run_in_threadpool as run_in_threadpool # noqafrom starlette.concurrency import ( # noqa run_until_first_complete as run_until_first_complete,)
_T = TypeVar("_T")
@asynccontextmanagerasync def contextmanager_in_threadpool( cm: ContextManager[_T],) -> AsyncGenerator[_T, None]: # blocking __exit__ from running waiting on a free thread # can create race conditions/deadlocks if the context manager itself # has its own internal pool (e.g. a database connection pool) # to avoid this we let __exit__ run without a capacity limit # since we're creating a new limiter for each call, any non-zero limit # works (1 is arbitrary) exit_limiter = CapacityLimiter(1) try: yield await run_in_threadpool(cm.__enter__) except Exception as e: ok = bool( await anyio.to_thread.run_sync( cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter ) ) if not ok: raise e else: await anyio.to_thread.run_sync( cm.__exit__, None, None, None, limiter=exit_limiter )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204from typing import ( Any, BinaryIO, Callable, Dict, Iterable, Optional, Type, TypeVar, cast,)
from fastapi._compat import ( PYDANTIC_V2, CoreSchema, GetJsonSchemaHandler, JsonSchemaValue, with_info_plain_validator_function,)from starlette.datastructures import URL as URL # noqa: F401from starlette.datastructures import Address as Address # noqa: F401from starlette.datastructures import FormData as FormData # noqa: F401from starlette.datastructures import Headers as Headers # noqa: F401from starlette.datastructures import QueryParams as QueryParams # noqa: F401from starlette.datastructures import State as State # noqa: F401from starlette.datastructures import UploadFile as StarletteUploadFilefrom typing_extensions import Annotated, Doc
class UploadFile(StarletteUploadFile): """ A file uploaded in a request.
Define it as a *path operation function* (or dependency) parameter.
If you are using a regular `def` function, you can use the `upload_file.file` attribute to access the raw standard Python file (blocking, not async), useful and needed for non-async code.
Read more about it in the [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/).
## Example
```python from typing import Annotated
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)}
@app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename} ``` """
file: Annotated[ BinaryIO, Doc("The standard Python file object (non-async)."), ] filename: Annotated[Optional[str], Doc("The original file name.")] size: Annotated[Optional[int], Doc("The size of the file in bytes.")] headers: Annotated[Headers, Doc("The headers of the request.")] content_type: Annotated[ Optional[str], Doc("The content type of the request, from the headers.") ]
async def write( self, data: Annotated[ bytes, Doc( """ The bytes to write to the file. """ ), ], ) -> None: """ Write some bytes to the file.
You normally wouldn't use this from a file you read in a request.
To be awaitable, compatible with async, this is run in threadpool. """ return await super().write(data)
async def read( self, size: Annotated[ int, Doc( """ The number of bytes to read from the file. """ ), ] = -1, ) -> bytes: """ Read some bytes from the file.
To be awaitable, compatible with async, this is run in threadpool. """ return await super().read(size)
async def seek( self, offset: Annotated[ int, Doc( """ The position in bytes to seek to in the file. """ ), ], ) -> None: """ Move to a position in the file.
Any next read or write will be done from that position.
To be awaitable, compatible with async, this is run in threadpool. """ return await super().seek(offset)
async def close(self) -> None: """ Close the file.
To be awaitable, compatible with async, this is run in threadpool. """ return await super().close()
@classmethod def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]: yield cls.validate
@classmethod def validate(cls: Type["UploadFile"], v: Any) -> Any: if not isinstance(v, StarletteUploadFile): raise ValueError(f"Expected UploadFile, received: {type(v)}") return v
@classmethod def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": if not isinstance(__input_value, StarletteUploadFile): raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") return cast(UploadFile, __input_value)
if not PYDANTIC_V2:
@classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: field_schema.update({"type": "string", "format": "binary"})
@classmethod def __get_pydantic_json_schema__( cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler ) -> JsonSchemaValue: return {"type": "string", "format": "binary"}
@classmethod def __get_pydantic_core_schema__( cls, source: Type[Any], handler: Callable[[Any], CoreSchema] ) -> CoreSchema: return with_info_plain_validator_function(cls._validate)
class DefaultPlaceholder: """ You shouldn't use this class directly.
It's used internally to recognize when a default value has been overwritten, even if the overridden default value was truthy. """
def __init__(self, value: Any): self.value = value
def __bool__(self) -> bool: return bool(self.value)
def __eq__(self, o: object) -> bool: return isinstance(o, DefaultPlaceholder) and o.value == self.value
DefaultType = TypeVar("DefaultType")
def Default(value: DefaultType) -> DefaultType: """ You shouldn't use this function directly.
It's used internally to recognize when a default value has been overwritten, even if the overridden default value was truthy. """ return DefaultPlaceholder(value) # type: ignore123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343import dataclassesimport datetimefrom collections import defaultdict, dequefrom decimal import Decimalfrom enum import Enumfrom ipaddress import ( IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network,)from pathlib import Path, PurePathfrom re import Patternfrom types import GeneratorTypefrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Unionfrom uuid import UUID
from fastapi.types import IncExfrom pydantic import BaseModelfrom pydantic.color import Colorfrom pydantic.networks import AnyUrl, NameEmailfrom pydantic.types import SecretBytes, SecretStrfrom typing_extensions import Annotated, Doc
from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump
# Taken from Pydantic v1 as isdef isoformat(o: Union[datetime.date, datetime.time]) -> str: return o.isoformat()
# Taken from Pydantic v1 as is# TODO: pv2 should this return strings instead?def decimal_encoder(dec_value: Decimal) -> Union[int, float]: """ Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0) where a integer (but not int typed) is used. Encoding this as a float results in failed round-tripping between encode and parse. Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0")) 1.0
>>> decimal_encoder(Decimal("1")) 1 """ if dec_value.as_tuple().exponent >= 0: # type: ignore[operator] return int(dec_value) else: return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { bytes: lambda o: o.decode(), Color: str, datetime.date: isoformat, datetime.datetime: isoformat, datetime.time: isoformat, datetime.timedelta: lambda td: td.total_seconds(), Decimal: decimal_encoder, Enum: lambda o: o.value, frozenset: list, deque: list, GeneratorType: list, IPv4Address: str, IPv4Interface: str, IPv4Network: str, IPv6Address: str, IPv6Interface: str, IPv6Network: str, NameEmail: str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, UUID: str, Url: str, AnyUrl: str,}
def generate_encoders_by_class_tuples( type_encoder_map: Dict[Any, Callable[[Any], Any]],) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( tuple ) for type_, encoder in type_encoder_map.items(): encoders_by_class_tuples[encoder] += (type_,) return encoders_by_class_tuples
encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)
def jsonable_encoder( obj: Annotated[ Any, Doc( """ The input object to convert to JSON. """ ), ], include: Annotated[ Optional[IncEx], Doc( """ Pydantic's `include` parameter, passed to Pydantic models to set the fields to include. """ ), ] = None, exclude: Annotated[ Optional[IncEx], Doc( """ Pydantic's `exclude` parameter, passed to Pydantic models to set the fields to exclude. """ ), ] = None, by_alias: Annotated[ bool, Doc( """ Pydantic's `by_alias` parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. In an API, if you set an alias, it's probably because you want to use it in the result, so you probably want to leave this set to `True`. """ ), ] = True, exclude_unset: Annotated[ bool, Doc( """ Pydantic's `exclude_unset` parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set (and that only had their default values). """ ), ] = False, exclude_defaults: Annotated[ bool, Doc( """ Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value, even when they were explicitly set. """ ), ] = False, exclude_none: Annotated[ bool, Doc( """ Pydantic's `exclude_none` parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a `None` value. """ ), ] = False, custom_encoder: Annotated[ Optional[Dict[Any, Callable[[Any], Any]]], Doc( """ Pydantic's `custom_encoder` parameter, passed to Pydantic models to define a custom encoder. """ ), ] = None, sqlalchemy_safe: Annotated[ bool, Doc( """ Exclude from the output any fields that start with the name `_sa`.
This is mainly a hack for compatibility with SQLAlchemy objects, they store internal SQLAlchemy-specific state in attributes named with `_sa`, and those objects can't (and shouldn't be) serialized to JSON. """ ), ] = True,) -> Any: """ Convert any object to something that can be encoded in JSON.
This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client.
You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON.
Read more about it in the [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). """ custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: return custom_encoder[type(obj)](obj) else: for encoder_type, encoder_instance in custom_encoder.items(): if isinstance(obj, encoder_type): return encoder_instance(obj) if include is not None and not isinstance(include, (set, dict)): include = set(include) if exclude is not None and not isinstance(exclude, (set, dict)): exclude = set(exclude) if isinstance(obj, BaseModel): # TODO: remove when deprecating Pydantic v1 encoders: Dict[Any, Any] = {} if not PYDANTIC_V2: encoders = getattr(obj.__config__, "json_encoders", {}) # type: ignore[attr-defined] if custom_encoder: encoders.update(custom_encoder) obj_dict = _model_dump( obj, mode="json", include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, exclude_defaults=exclude_defaults, ) if "__root__" in obj_dict: obj_dict = obj_dict["__root__"] return jsonable_encoder( obj_dict, exclude_none=exclude_none, exclude_defaults=exclude_defaults, # TODO: remove when deprecating Pydantic v1 custom_encoder=encoders, sqlalchemy_safe=sqlalchemy_safe, ) if dataclasses.is_dataclass(obj): obj_dict = dataclasses.asdict(obj) return jsonable_encoder( obj_dict, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) if isinstance(obj, Enum): return obj.value if isinstance(obj, PurePath): return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj if isinstance(obj, UndefinedType): return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) if include is not None: allowed_keys &= set(include) if exclude is not None: allowed_keys -= set(exclude) for key, value in obj.items(): if ( ( not sqlalchemy_safe or (not isinstance(key, str)) or (not key.startswith("_sa")) ) and (value is not None or not exclude_none) and key in allowed_keys ): encoded_key = jsonable_encoder( key, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_value = jsonable_encoder( value, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_dict[encoded_key] = encoded_value return encoded_dict if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): encoded_list = [] for item in obj: encoded_list.append( jsonable_encoder( item, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) ) return encoded_list
if type(obj) in ENCODERS_BY_TYPE: return ENCODERS_BY_TYPE[type(obj)](obj) for encoder, classes_tuple in encoders_by_class_tuples.items(): if isinstance(obj, classes_tuple): return encoder(obj)
try: data = dict(obj) except Exception as e: errors: List[Exception] = [] errors.append(e) try: data = vars(obj) except Exception as e: errors.append(e) raise ValueError(errors) from e return jsonable_encoder( data, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, )12345678910111213141516171819202122232425262728293031323334from fastapi.encoders import jsonable_encoderfrom fastapi.exceptions import RequestValidationError, WebSocketRequestValidationErrorfrom fastapi.utils import is_body_allowed_for_status_codefrom fastapi.websockets import WebSocketfrom starlette.exceptions import HTTPExceptionfrom starlette.requests import Requestfrom starlette.responses import JSONResponse, Responsefrom starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION
async def http_exception_handler(request: Request, exc: HTTPException) -> Response: headers = getattr(exc, "headers", None) if not is_body_allowed_for_status_code(exc.status_code): return Response(status_code=exc.status_code, headers=headers) return JSONResponse( {"detail": exc.detail}, status_code=exc.status_code, headers=headers )
async def request_validation_exception_handler( request: Request, exc: RequestValidationError) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(exc.errors())}, )
async def websocket_request_validation_exception_handler( websocket: WebSocket, exc: WebSocketRequestValidationError) -> None: await websocket.close( code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors()) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176from typing import Any, Dict, Optional, Sequence, Type, Union
from pydantic import BaseModel, create_modelfrom starlette.exceptions import HTTPException as StarletteHTTPExceptionfrom starlette.exceptions import WebSocketException as StarletteWebSocketExceptionfrom typing_extensions import Annotated, Doc
class HTTPException(StarletteHTTPException): """ An HTTP exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code.
Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
## Example
```python from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}") async def read_item(item_id: str): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return {"item": items[item_id]} ``` """
def __init__( self, status_code: Annotated[ int, Doc( """ HTTP status code to send to the client. """ ), ], detail: Annotated[ Any, Doc( """ Any data to be sent to the client in the `detail` key of the JSON response. """ ), ] = None, headers: Annotated[ Optional[Dict[str, str]], Doc( """ Any headers to send to the client in the response. """ ), ] = None, ) -> None: super().__init__(status_code=status_code, detail=detail, headers=headers)
class WebSocketException(StarletteWebSocketException): """ A WebSocket exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code.
Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
## Example
```python from typing import Annotated
from fastapi import ( Cookie, FastAPI, WebSocket, WebSocketException, status, )
app = FastAPI()
@app.websocket("/items/{item_id}/ws") async def websocket_endpoint( *, websocket: WebSocket, session: Annotated[str | None, Cookie()] = None, item_id: str, ): if session is None: raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Session cookie is: {session}") await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") ``` """
def __init__( self, code: Annotated[ int, Doc( """ A closing code from the [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). """ ), ], reason: Annotated[ Union[str, None], Doc( """ The reason to close the WebSocket connection.
It is UTF-8-encoded data. The interpretation of the reason is up to the application, it is not specified by the WebSocket specification.
It could contain text that could be human-readable or interpretable by the client code, etc. """ ), ] = None, ) -> None: super().__init__(code=code, reason=reason)
RequestErrorModel: Type[BaseModel] = create_model("Request")WebSocketErrorModel: Type[BaseModel] = create_model("WebSocket")
class FastAPIError(RuntimeError): """ A generic, FastAPI-specific error. """
class ValidationException(Exception): def __init__(self, errors: Sequence[Any]) -> None: self._errors = errors
def errors(self) -> Sequence[Any]: return self._errors
class RequestValidationError(ValidationException): def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: super().__init__(errors) self.body = body
class WebSocketRequestValidationError(ValidationException): pass
class ResponseValidationError(ValidationException): def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: super().__init__(errors) self.body = body
def __str__(self) -> str: message = f"{len(self._errors)} validation errors:\n" for err in self._errors: message += f" {err}\n" return message123import logging
logger = logging.getLogger("fastapi")123METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"}REF_PREFIX = "#/components/schemas/"REF_TEMPLATE = "#/components/schemas/{model}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344import jsonfrom typing import Any, Dict, Optional
from fastapi.encoders import jsonable_encoderfrom starlette.responses import HTMLResponsefrom typing_extensions import Annotated, Doc
swagger_ui_default_parameters: Annotated[ Dict[str, Any], Doc( """ Default configurations for Swagger UI.
You can use it as a template to add any other configurations needed. """ ),] = { "dom_id": "#swagger-ui", "layout": "BaseLayout", "deepLinking": True, "showExtensions": True, "showCommonExtensions": True,}
def get_swagger_ui_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that Swagger UI should load and use.
This is normally done automatically by FastAPI using the default URL `/openapi.json`. """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. """ ), ], swagger_js_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI JavaScript.
It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI CSS.
It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", oauth2_redirect_url: Annotated[ Optional[str], Doc( """ The OAuth2 redirect URL, it is normally automatically handled by FastAPI. """ ), ] = None, init_oauth: Annotated[ Optional[Dict[str, Any]], Doc( """ A dictionary with Swagger UI OAuth2 initialization configurations. """ ), ] = None, swagger_ui_parameters: Annotated[ Optional[Dict[str, Any]], Doc( """ Configuration parameters for Swagger UI.
It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters]. """ ), ] = None,) -> HTMLResponse: """ Generate and return the HTML that loads Swagger UI for the interactive API docs (normally served at `/docs`).
You would only call this function yourself if you needed to override some parts, for example the URLs to use to load Swagger UI's JavaScript and CSS.
Read more about it in the [FastAPI docs for Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) and the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). """ current_swagger_ui_parameters = swagger_ui_default_parameters.copy() if swagger_ui_parameters: current_swagger_ui_parameters.update(swagger_ui_parameters)
html = f""" <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="{swagger_css_url}"> <link rel="shortcut icon" href="{swagger_favicon_url}"> <title>{title}</title> </head> <body> <div id="swagger-ui"> </div> <script src="{swagger_js_url}"></script> <!-- `SwaggerUIBundle` is now available on the page --> <script> const ui = SwaggerUIBundle({{ url: '{openapi_url}', """
for key, value in current_swagger_ui_parameters.items(): html += f"{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\n"
if oauth2_redirect_url: html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}',"
html += """ presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], })"""
if init_oauth: html += f""" ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))}) """
html += """ </script> </body> </html> """ return HTMLResponse(html)
def get_redoc_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that ReDoc should load and use.
This is normally done automatically by FastAPI using the default URL `/openapi.json`. """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. """ ), ], redoc_js_url: Annotated[ str, Doc( """ The URL to use to load the ReDoc JavaScript.
It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js", redoc_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", with_google_fonts: Annotated[ bool, Doc( """ Load and use Google Fonts. """ ), ] = True,) -> HTMLResponse: """ Generate and return the HTML response that loads ReDoc for the alternative API docs (normally served at `/redoc`).
You would only call this function yourself if you needed to override some parts, for example the URLs to use to load ReDoc's JavaScript and CSS.
Read more about it in the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). """ html = f""" <!DOCTYPE html> <html> <head> <title>{title}</title> <!-- needed for adaptive design --> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> """ if with_google_fonts: html += """ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet"> """ html += f""" <link rel="shortcut icon" href="{redoc_favicon_url}"> <!-- ReDoc doesn't change outer page styles --> <style> body {{ margin: 0; padding: 0; }} </style> </head> <body> <noscript> ReDoc requires Javascript to function. Please enable it to browse the documentation. </noscript> <redoc spec-url="{openapi_url}"></redoc> <script src="{redoc_js_url}"> </script> </body> </html> """ return HTMLResponse(html)
def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: """ Generate the HTML response with the OAuth2 redirection for Swagger UI.
You normally don't need to use or change this. """ # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ <!doctype html> <html lang="en-US"> <head> <title>Swagger UI: OAuth2 Redirect</title> </head> <body> <script> 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1).replace('?', '&'); } else { qp = location.search.substring(1); }
arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';}); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {};
isValid = qp.state === sentState;
if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server." }); }
if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); }
oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server." }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); }
if (document.readyState !== 'loading') { run(); } else { document.addEventListener('DOMContentLoaded', function () { run(); }); } </script> </body> </html> """ return HTMLResponse(content=html)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445from enum import Enumfrom typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union
from fastapi._compat import ( PYDANTIC_V2, CoreSchema, GetJsonSchemaHandler, JsonSchemaValue, _model_rebuild, with_info_plain_validator_function,)from fastapi.logger import loggerfrom pydantic import AnyUrl, BaseModel, Fieldfrom typing_extensions import Annotated, Literal, TypedDictfrom typing_extensions import deprecated as typing_deprecated
try: import email_validator
assert email_validator # make autoflake ignore the unused import from pydantic import EmailStrexcept ImportError: # pragma: no cover
class EmailStr(str): # type: ignore @classmethod def __get_validators__(cls) -> Iterable[Callable[..., Any]]: yield cls.validate
@classmethod def validate(cls, v: Any) -> str: logger.warning( "email-validator not installed, email fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(v)
@classmethod def _validate(cls, __input_value: Any, _: Any) -> str: logger.warning( "email-validator not installed, email fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(__input_value)
@classmethod def __get_pydantic_json_schema__( cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler ) -> JsonSchemaValue: return {"type": "string", "format": "email"}
@classmethod def __get_pydantic_core_schema__( cls, source: Type[Any], handler: Callable[[Any], CoreSchema] ) -> CoreSchema: return with_info_plain_validator_function(cls._validate)
class BaseModelWithConfig(BaseModel): if PYDANTIC_V2: model_config = {"extra": "allow"}
else:
class Config: extra = "allow"
class Contact(BaseModelWithConfig): name: Optional[str] = None url: Optional[AnyUrl] = None email: Optional[EmailStr] = None
class License(BaseModelWithConfig): name: str identifier: Optional[str] = None url: Optional[AnyUrl] = None
class Info(BaseModelWithConfig): title: str summary: Optional[str] = None description: Optional[str] = None termsOfService: Optional[str] = None contact: Optional[Contact] = None license: Optional[License] = None version: str
class ServerVariable(BaseModelWithConfig): enum: Annotated[Optional[List[str]], Field(min_length=1)] = None default: str description: Optional[str] = None
class Server(BaseModelWithConfig): url: Union[AnyUrl, str] description: Optional[str] = None variables: Optional[Dict[str, ServerVariable]] = None
class Reference(BaseModel): ref: str = Field(alias="$ref")
class Discriminator(BaseModel): propertyName: str mapping: Optional[Dict[str, str]] = None
class XML(BaseModelWithConfig): name: Optional[str] = None namespace: Optional[str] = None prefix: Optional[str] = None attribute: Optional[bool] = None wrapped: Optional[bool] = None
class ExternalDocumentation(BaseModelWithConfig): description: Optional[str] = None url: AnyUrl
class Schema(BaseModelWithConfig): # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu # Core Vocabulary schema_: Optional[str] = Field(default=None, alias="$schema") vocabulary: Optional[str] = Field(default=None, alias="$vocabulary") id: Optional[str] = Field(default=None, alias="$id") anchor: Optional[str] = Field(default=None, alias="$anchor") dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor") ref: Optional[str] = Field(default=None, alias="$ref") dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef") defs: Optional[Dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs") comment: Optional[str] = Field(default=None, alias="$comment") # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s # A Vocabulary for Applying Subschemas allOf: Optional[List["SchemaOrBool"]] = None anyOf: Optional[List["SchemaOrBool"]] = None oneOf: Optional[List["SchemaOrBool"]] = None not_: Optional["SchemaOrBool"] = Field(default=None, alias="not") if_: Optional["SchemaOrBool"] = Field(default=None, alias="if") then: Optional["SchemaOrBool"] = None else_: Optional["SchemaOrBool"] = Field(default=None, alias="else") dependentSchemas: Optional[Dict[str, "SchemaOrBool"]] = None prefixItems: Optional[List["SchemaOrBool"]] = None # TODO: uncomment and remove below when deprecating Pydantic v1 # It generales a list of schemas for tuples, before prefixItems was available # items: Optional["SchemaOrBool"] = None items: Optional[Union["SchemaOrBool", List["SchemaOrBool"]]] = None contains: Optional["SchemaOrBool"] = None properties: Optional[Dict[str, "SchemaOrBool"]] = None patternProperties: Optional[Dict[str, "SchemaOrBool"]] = None additionalProperties: Optional["SchemaOrBool"] = None propertyNames: Optional["SchemaOrBool"] = None unevaluatedItems: Optional["SchemaOrBool"] = None unevaluatedProperties: Optional["SchemaOrBool"] = None # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural # A Vocabulary for Structural Validation type: Optional[str] = None enum: Optional[List[Any]] = None const: Optional[Any] = None multipleOf: Optional[float] = Field(default=None, gt=0) maximum: Optional[float] = None exclusiveMaximum: Optional[float] = None minimum: Optional[float] = None exclusiveMinimum: Optional[float] = None maxLength: Optional[int] = Field(default=None, ge=0) minLength: Optional[int] = Field(default=None, ge=0) pattern: Optional[str] = None maxItems: Optional[int] = Field(default=None, ge=0) minItems: Optional[int] = Field(default=None, ge=0) uniqueItems: Optional[bool] = None maxContains: Optional[int] = Field(default=None, ge=0) minContains: Optional[int] = Field(default=None, ge=0) maxProperties: Optional[int] = Field(default=None, ge=0) minProperties: Optional[int] = Field(default=None, ge=0) required: Optional[List[str]] = None dependentRequired: Optional[Dict[str, Set[str]]] = None # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c # Vocabularies for Semantic Content With "format" format: Optional[str] = None # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten # A Vocabulary for the Contents of String-Encoded Data contentEncoding: Optional[str] = None contentMediaType: Optional[str] = None contentSchema: Optional["SchemaOrBool"] = None # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta # A Vocabulary for Basic Meta-Data Annotations title: Optional[str] = None description: Optional[str] = None default: Optional[Any] = None deprecated: Optional[bool] = None readOnly: Optional[bool] = None writeOnly: Optional[bool] = None examples: Optional[List[Any]] = None # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object # Schema Object discriminator: Optional[Discriminator] = None xml: Optional[XML] = None externalDocs: Optional[ExternalDocumentation] = None example: Annotated[ Optional[Any], typing_deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = None
# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents# A JSON Schema MUST be an object or a boolean.SchemaOrBool = Union[Schema, bool]
class Example(TypedDict, total=False): summary: Optional[str] description: Optional[str] value: Optional[Any] externalValue: Optional[AnyUrl]
if PYDANTIC_V2: # type: ignore [misc] __pydantic_config__ = {"extra": "allow"}
else:
class Config: extra = "allow"
class ParameterInType(Enum): query = "query" header = "header" path = "path" cookie = "cookie"
class Encoding(BaseModelWithConfig): contentType: Optional[str] = None headers: Optional[Dict[str, Union["Header", Reference]]] = None style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None
class MediaType(BaseModelWithConfig): schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None
class ParameterBase(BaseModelWithConfig): description: Optional[str] = None required: Optional[bool] = None deprecated: Optional[bool] = None # Serialization rules for simple scenarios style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None # Serialization rules for more complex scenarios content: Optional[Dict[str, MediaType]] = None
class Parameter(ParameterBase): name: str in_: ParameterInType = Field(alias="in")
class Header(ParameterBase): pass
class RequestBody(BaseModelWithConfig): description: Optional[str] = None content: Dict[str, MediaType] required: Optional[bool] = None
class Link(BaseModelWithConfig): operationRef: Optional[str] = None operationId: Optional[str] = None parameters: Optional[Dict[str, Union[Any, str]]] = None requestBody: Optional[Union[Any, str]] = None description: Optional[str] = None server: Optional[Server] = None
class Response(BaseModelWithConfig): description: str headers: Optional[Dict[str, Union[Header, Reference]]] = None content: Optional[Dict[str, MediaType]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None
class Operation(BaseModelWithConfig): tags: Optional[List[str]] = None summary: Optional[str] = None description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None operationId: Optional[str] = None parameters: Optional[List[Union[Parameter, Reference]]] = None requestBody: Optional[Union[RequestBody, Reference]] = None # Using Any for Specification Extensions responses: Optional[Dict[str, Union[Response, Any]]] = None callbacks: Optional[Dict[str, Union[Dict[str, "PathItem"], Reference]]] = None deprecated: Optional[bool] = None security: Optional[List[Dict[str, List[str]]]] = None servers: Optional[List[Server]] = None
class PathItem(BaseModelWithConfig): ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None get: Optional[Operation] = None put: Optional[Operation] = None post: Optional[Operation] = None delete: Optional[Operation] = None options: Optional[Operation] = None head: Optional[Operation] = None patch: Optional[Operation] = None trace: Optional[Operation] = None servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None
class SecuritySchemeType(Enum): apiKey = "apiKey" http = "http" oauth2 = "oauth2" openIdConnect = "openIdConnect"
class SecurityBase(BaseModelWithConfig): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None
class APIKeyIn(Enum): query = "query" header = "header" cookie = "cookie"
class APIKey(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type") in_: APIKeyIn = Field(alias="in") name: str
class HTTPBase(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type") scheme: str
class HTTPBearer(HTTPBase): scheme: Literal["bearer"] = "bearer" bearerFormat: Optional[str] = None
class OAuthFlow(BaseModelWithConfig): refreshUrl: Optional[str] = None scopes: Dict[str, str] = {}
class OAuthFlowImplicit(OAuthFlow): authorizationUrl: str
class OAuthFlowPassword(OAuthFlow): tokenUrl: str
class OAuthFlowClientCredentials(OAuthFlow): tokenUrl: str
class OAuthFlowAuthorizationCode(OAuthFlow): authorizationUrl: str tokenUrl: str
class OAuthFlows(BaseModelWithConfig): implicit: Optional[OAuthFlowImplicit] = None password: Optional[OAuthFlowPassword] = None clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None
class OAuth2(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") flows: OAuthFlows
class OpenIdConnect(SecurityBase): type_: SecuritySchemeType = Field( default=SecuritySchemeType.openIdConnect, alias="type" ) openIdConnectUrl: str
SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer]
class Components(BaseModelWithConfig): schemas: Optional[Dict[str, Union[Schema, Reference]]] = None responses: Optional[Dict[str, Union[Response, Reference]]] = None parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None requestBodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None headers: Optional[Dict[str, Union[Header, Reference]]] = None securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None # Using Any for Specification Extensions callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None
class Tag(BaseModelWithConfig): name: str description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None
class OpenAPI(BaseModelWithConfig): openapi: str info: Info jsonSchemaDialect: Optional[str] = None servers: Optional[List[Server]] = None # Using Any for Specification Extensions paths: Optional[Dict[str, Union[PathItem, Any]]] = None webhooks: Optional[Dict[str, Union[PathItem, Reference]]] = None components: Optional[Components] = None security: Optional[List[Dict[str, List[str]]]] = None tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None
_model_rebuild(Schema)_model_rebuild(Operation)_model_rebuild(Encoding)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569import http.clientimport inspectimport warningsfrom typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast
from fastapi import routingfrom fastapi._compat import ( GenerateJsonSchema, JsonSchemaValue, ModelField, Undefined, get_compat_model_name_map, get_definitions, get_schema_from_model_field, lenient_issubclass,)from fastapi.datastructures import DefaultPlaceholderfrom fastapi.dependencies.models import Dependantfrom fastapi.dependencies.utils import ( _get_flat_fields_from_params, get_flat_dependant, get_flat_params,)from fastapi.encoders import jsonable_encoderfrom fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATEfrom fastapi.openapi.models import OpenAPIfrom fastapi.params import Body, ParamTypesfrom fastapi.responses import Responsefrom fastapi.types import ModelNameMapfrom fastapi.utils import ( deep_dict_update, generate_operation_id_for_path, is_body_allowed_for_status_code,)from pydantic import BaseModelfrom starlette.responses import JSONResponsefrom starlette.routing import BaseRoutefrom starlette.status import HTTP_422_UNPROCESSABLE_ENTITYfrom typing_extensions import Literal
validation_error_definition = { "title": "ValidationError", "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"],}
validation_error_response_definition = { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": REF_PREFIX + "ValidationError"}, } },}
status_code_ranges: Dict[str, str] = { "1XX": "Information", "2XX": "Success", "3XX": "Redirection", "4XX": "Client Error", "5XX": "Server Error", "DEFAULT": "Default Response",}
def get_openapi_security_definitions( flat_dependant: Dependant,) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: security_definitions = {} operation_security = [] for security_requirement in flat_dependant.security_requirements: security_definition = jsonable_encoder( security_requirement.security_scheme.model, by_alias=True, exclude_none=True, ) security_name = security_requirement.security_scheme.scheme_name security_definitions[security_name] = security_definition operation_security.append({security_name: security_requirement.scopes}) return security_definitions, operation_security
def _get_openapi_operation_parameters( *, dependant: Dependant, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True,) -> List[Dict[str, Any]]: parameters = [] flat_dependant = get_flat_dependant(dependant, skip_repeats=True) path_params = _get_flat_fields_from_params(flat_dependant.path_params) query_params = _get_flat_fields_from_params(flat_dependant.query_params) header_params = _get_flat_fields_from_params(flat_dependant.header_params) cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) parameter_groups = [ (ParamTypes.path, path_params), (ParamTypes.query, query_params), (ParamTypes.header, header_params), (ParamTypes.cookie, cookie_params), ] default_convert_underscores = True if len(flat_dependant.header_params) == 1: first_field = flat_dependant.header_params[0] if lenient_issubclass(first_field.type_, BaseModel): default_convert_underscores = getattr( first_field.field_info, "convert_underscores", True ) for param_type, param_group in parameter_groups: for param in param_group: field_info = param.field_info # field_info = cast(Param, field_info) if not getattr(field_info, "include_in_schema", True): continue param_schema = get_schema_from_model_field( field=param, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) name = param.alias convert_underscores = getattr( param.field_info, "convert_underscores", default_convert_underscores, ) if ( param_type == ParamTypes.header and param.alias == param.name and convert_underscores ): name = param.name.replace("_", "-")
parameter = { "name": name, "in": param_type.value, "required": param.required, "schema": param_schema, } if field_info.description: parameter["description"] = field_info.description openapi_examples = getattr(field_info, "openapi_examples", None) example = getattr(field_info, "example", None) if openapi_examples: parameter["examples"] = jsonable_encoder(openapi_examples) elif example != Undefined: parameter["example"] = jsonable_encoder(example) if getattr(field_info, "deprecated", None): parameter["deprecated"] = True parameters.append(parameter) return parameters
def get_openapi_operation_request_body( *, body_field: Optional[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True,) -> Optional[Dict[str, Any]]: if not body_field: return None assert isinstance(body_field, ModelField) body_schema = get_schema_from_model_field( field=body_field, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) field_info = cast(Body, body_field.field_info) request_media_type = field_info.media_type required = body_field.required request_body_oai: Dict[str, Any] = {} if required: request_body_oai["required"] = required request_media_content: Dict[str, Any] = {"schema": body_schema} if field_info.openapi_examples: request_media_content["examples"] = jsonable_encoder( field_info.openapi_examples ) elif field_info.example != Undefined: request_media_content["example"] = jsonable_encoder(field_info.example) request_body_oai["content"] = {request_media_type: request_media_content} return request_body_oai
def generate_operation_id( *, route: routing.APIRoute, method: str) -> str: # pragma: nocover warnings.warn( "fastapi.openapi.utils.generate_operation_id() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) if route.operation_id: return route.operation_id path: str = route.path_format return generate_operation_id_for_path(name=route.name, path=path, method=method)
def generate_operation_summary(*, route: routing.APIRoute, method: str) -> str: if route.summary: return route.summary return route.name.replace("_", " ").title()
def get_openapi_operation_metadata( *, route: routing.APIRoute, method: str, operation_ids: Set[str]) -> Dict[str, Any]: operation: Dict[str, Any] = {} if route.tags: operation["tags"] = route.tags operation["summary"] = generate_operation_summary(route=route, method=method) if route.description: operation["description"] = route.description operation_id = route.operation_id or route.unique_id if operation_id in operation_ids: message = ( f"Duplicate Operation ID {operation_id} for function " + f"{route.endpoint.__name__}" ) file_name = getattr(route.endpoint, "__globals__", {}).get("__file__") if file_name: message += f" at {file_name}" warnings.warn(message, stacklevel=1) operation_ids.add(operation_id) operation["operationId"] = operation_id if route.deprecated: operation["deprecated"] = route.deprecated return operation
def get_openapi_path( *, route: routing.APIRoute, operation_ids: Set[str], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True,) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]: path = {} security_schemes: Dict[str, Any] = {} definitions: Dict[str, Any] = {} assert route.methods is not None, "Methods must be a list" if isinstance(route.response_class, DefaultPlaceholder): current_response_class: Type[Response] = route.response_class.value else: current_response_class = route.response_class assert current_response_class, "A response class is needed to generate OpenAPI" route_response_media_type: Optional[str] = current_response_class.media_type if route.include_in_schema: for method in route.methods: operation = get_openapi_operation_metadata( route=route, method=method, operation_ids=operation_ids ) parameters: List[Dict[str, Any]] = [] flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True) security_definitions, operation_security = get_openapi_security_definitions( flat_dependant=flat_dependant ) if operation_security: operation.setdefault("security", []).extend(operation_security) if security_definitions: security_schemes.update(security_definitions) operation_parameters = _get_openapi_operation_parameters( dependant=route.dependant, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) parameters.extend(operation_parameters) if parameters: all_parameters = { (param["in"], param["name"]): param for param in parameters } required_parameters = { (param["in"], param["name"]): param for param in parameters if param.get("required") } # Make sure required definitions of the same parameter take precedence # over non-required definitions all_parameters.update(required_parameters) operation["parameters"] = list(all_parameters.values()) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( body_field=route.body_field, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if request_body_oai: operation["requestBody"] = request_body_oai if route.callbacks: callbacks = {} for callback in route.callbacks: if isinstance(callback, routing.APIRoute): ( cb_path, cb_security_schemes, cb_definitions, ) = get_openapi_path( route=callback, operation_ids=operation_ids, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) callbacks[callback.name] = {callback.path: cb_path} operation["callbacks"] = callbacks if route.status_code is not None: status_code = str(route.status_code) else: # It would probably make more sense for all response classes to have an # explicit default status_code, and to extract it from them, instead of # doing this inspection tricks, that would probably be in the future # TODO: probably make status_code a default class attribute for all # responses in Starlette response_signature = inspect.signature(current_response_class.__init__) status_code_param = response_signature.parameters.get("status_code") if status_code_param is not None: if isinstance(status_code_param.default, int): status_code = str(status_code_param.default) operation.setdefault("responses", {}).setdefault(status_code, {})[ "description" ] = route.response_description if route_response_media_type and is_body_allowed_for_status_code( route.status_code ): response_schema = {"type": "string"} if lenient_issubclass(current_response_class, JSONResponse): if route.response_field: response_schema = get_schema_from_model_field( field=route.response_field, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) else: response_schema = {} operation.setdefault("responses", {}).setdefault( status_code, {} ).setdefault("content", {}).setdefault(route_response_media_type, {})[ "schema" ] = response_schema if route.responses: operation_responses = operation.setdefault("responses", {}) for ( additional_status_code, additional_response, ) in route.responses.items(): process_response = additional_response.copy() process_response.pop("model", None) status_code_key = str(additional_status_code).upper() if status_code_key == "DEFAULT": status_code_key = "default" openapi_response = operation_responses.setdefault( status_code_key, {} ) assert isinstance(process_response, dict), ( "An additional response must be a dict" ) field = route.response_fields.get(additional_status_code) additional_field_schema: Optional[Dict[str, Any]] = None if field: additional_field_schema = get_schema_from_model_field( field=field, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) media_type = route_response_media_type or "application/json" additional_schema = ( process_response.setdefault("content", {}) .setdefault(media_type, {}) .setdefault("schema", {}) ) deep_dict_update(additional_schema, additional_field_schema) status_text: Optional[str] = status_code_ranges.get( str(additional_status_code).upper() ) or http.client.responses.get(int(additional_status_code)) description = ( process_response.get("description") or openapi_response.get("description") or status_text or "Additional Response" ) deep_dict_update(openapi_response, process_response) openapi_response["description"] = description http422 = str(HTTP_422_UNPROCESSABLE_ENTITY) all_route_params = get_flat_params(route.dependant) if (all_route_params or route.body_field) and not any( status in operation["responses"] for status in [http422, "4XX", "default"] ): operation["responses"][http422] = { "description": "Validation Error", "content": { "application/json": { "schema": {"$ref": REF_PREFIX + "HTTPValidationError"} } }, } if "ValidationError" not in definitions: definitions.update( { "ValidationError": validation_error_definition, "HTTPValidationError": validation_error_response_definition, } ) if route.openapi_extra: deep_dict_update(operation, route.openapi_extra) path[method.lower()] = operation return path, security_schemes, definitions
def get_fields_from_routes( routes: Sequence[BaseRoute],) -> List[ModelField]: body_fields_from_routes: List[ModelField] = [] responses_from_routes: List[ModelField] = [] request_fields_from_routes: List[ModelField] = [] callback_flat_models: List[ModelField] = [] for route in routes: if getattr(route, "include_in_schema", None) and isinstance( route, routing.APIRoute ): if route.body_field: assert isinstance(route.body_field, ModelField), ( "A request body must be a Pydantic Field" ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) if route.response_fields: responses_from_routes.extend(route.response_fields.values()) if route.callbacks: callback_flat_models.extend(get_fields_from_routes(route.callbacks)) params = get_flat_params(route.dependant) request_fields_from_routes.extend(params)
flat_models = callback_flat_models + list( body_fields_from_routes + responses_from_routes + request_fields_from_routes ) return flat_models
def get_openapi( *, title: str, version: str, openapi_version: str = "3.1.0", summary: Optional[str] = None, description: Optional[str] = None, routes: Sequence[BaseRoute], webhooks: Optional[Sequence[BaseRoute]] = None, tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[str, Any]]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[str, Any]]] = None, license_info: Optional[Dict[str, Union[str, Any]]] = None, separate_input_output_schemas: bool = True,) -> Dict[str, Any]: info: Dict[str, Any] = {"title": title, "version": version} if summary: info["summary"] = summary if description: info["description"] = description if terms_of_service: info["termsOfService"] = terms_of_service if contact: info["contact"] = contact if license_info: info["license"] = license_info output: Dict[str, Any] = {"openapi": openapi_version, "info": info} if servers: output["servers"] = servers components: Dict[str, Dict[str, Any]] = {} paths: Dict[str, Dict[str, Any]] = {} webhook_paths: Dict[str, Dict[str, Any]] = {} operation_ids: Set[str] = set() all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or [])) model_name_map = get_compat_model_name_map(all_fields) schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) field_mapping, definitions = get_definitions( fields=all_fields, schema_generator=schema_generator, model_name_map=model_name_map, separate_input_output_schemas=separate_input_output_schemas, ) for route in routes or []: if isinstance(route, routing.APIRoute): result = get_openapi_path( route=route, operation_ids=operation_ids, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if result: path, security_schemes, path_definitions = result if path: paths.setdefault(route.path_format, {}).update(path) if security_schemes: components.setdefault("securitySchemes", {}).update( security_schemes ) if path_definitions: definitions.update(path_definitions) for webhook in webhooks or []: if isinstance(webhook, routing.APIRoute): result = get_openapi_path( route=webhook, operation_ids=operation_ids, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if result: path, security_schemes, path_definitions = result if path: webhook_paths.setdefault(webhook.path_format, {}).update(path) if security_schemes: components.setdefault("securitySchemes", {}).update( security_schemes ) if path_definitions: definitions.update(path_definitions) if definitions: components["schemas"] = {k: definitions[k] for k in sorted(definitions)} if components: output["components"] = components output["paths"] = paths if webhook_paths: output["webhooks"] = webhook_paths if tags: output["tags"] = tags return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360from typing import Any, Callable, Dict, List, Optional, Sequence, Union
from fastapi import paramsfrom fastapi._compat import Undefinedfrom fastapi.openapi.models import Examplefrom typing_extensions import Annotated, Doc, deprecated
_Unset: Any = Undefined
def Path( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = ..., *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: """ Declare a path parameter for a *path operation*.
Read more about it in the [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).
```python from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], ): return {"item_id": item_id} ``` """ return params.Path( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Query( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.Query( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Header( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, convert_underscores: Annotated[ bool, Doc( """ Automatically convert underscores to hyphens in the parameter field name.
Read more about it in the [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) """ ), ] = True, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.Header( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, convert_underscores=convert_underscores, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Cookie( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.Cookie( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Body( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, embed: Annotated[ Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a key instead of being the JSON body itself.
This happens automatically when more than one `Body` parameter is declared.
Read more about it in the [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), ] = None, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/json", alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.Body( default=default, default_factory=default_factory, embed=embed, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Form( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/x-www-form-urlencoded", alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.Form( default=default, default_factory=default_factory, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def File( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value.
This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "multipart/form-data", alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field.
This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[List[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ Optional[Dict[str, Example]], Doc( """ OpenAPI-specific examples.
It will be added to the generated OpenAPI (e.g. visible at `/docs`).
Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this.
Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated.
It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available.
This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[Dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ],) -> Any: return params.File( default=default, default_factory=default_factory, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
def Depends( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request.
Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True,) -> Any: """ Declare a FastAPI dependency.
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).
**Example**
```python from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return commons ``` """ return params.Depends(dependency=dependency, use_cache=use_cache)
def Security( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, scopes: Annotated[ Optional[Sequence[str]], Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency.
The term "scope" comes from the OAuth2 specification, it seems to be intentionally vague and interpretable. It normally refers to permissions, in cases to roles.
These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. ) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request.
Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True,) -> Any: """ Declare a FastAPI Security dependency.
The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at `/docs`).
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
**Example**
```python from typing import Annotated
from fastapi import Security, FastAPI
from .db import User from .security import get_current_active_user
app = FastAPI()
@app.get("/users/me/items/") async def read_own_items( current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] ): return [{"item_id": "Foo", "owner": current_user.username}] ``` """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786import warningsfrom enum import Enumfrom typing import Any, Callable, Dict, List, Optional, Sequence, Union
from fastapi.openapi.models import Examplefrom pydantic.fields import FieldInfofrom typing_extensions import Annotated, deprecated
from ._compat import ( PYDANTIC_V2, PYDANTIC_VERSION_MINOR_TUPLE, Undefined,)
_Unset: Any = Undefined
class ParamTypes(Enum): query = "query" header = "header" path = "path" cookie = "cookie"
class Param(FieldInfo): in_: ParamTypes
def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", category=DeprecationWarning, stacklevel=4, ) self.example = example self.include_in_schema = include_in_schema self.openapi_examples = openapi_examples kwargs = dict( default=default, default_factory=default_factory, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, ) if examples is not None: kwargs["examples"] = examples if regex is not None: warnings.warn( "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): self.deprecated = deprecated else: kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { "annotation": annotation, "alias_priority": alias_priority, "validation_alias": validation_alias, "serialization_alias": serialization_alias, "strict": strict, "json_schema_extra": current_json_schema_extra, } ) kwargs["pattern"] = pattern or regex else: kwargs["regex"] = pattern or regex kwargs.update(**current_json_schema_extra) use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})"
class Path(Param): in_ = ParamTypes.path
def __init__( self, default: Any = ..., *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): assert default is ..., "Path parameters cannot have a default value" self.in_ = self.in_ super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class Query(Param): in_ = ParamTypes.query
def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class Header(Param): in_ = ParamTypes.header
def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, convert_underscores: bool = True, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.convert_underscores = convert_underscores super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class Cookie(Param): in_ = ParamTypes.cookie
def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class Body(FieldInfo): def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", category=DeprecationWarning, stacklevel=4, ) self.example = example self.include_in_schema = include_in_schema self.openapi_examples = openapi_examples kwargs = dict( default=default, default_factory=default_factory, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, ) if examples is not None: kwargs["examples"] = examples if regex is not None: warnings.warn( "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): self.deprecated = deprecated else: kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { "annotation": annotation, "alias_priority": alias_priority, "validation_alias": validation_alias, "serialization_alias": serialization_alias, "strict": strict, "json_schema_extra": current_json_schema_extra, } ) kwargs["pattern"] = pattern or regex else: kwargs["regex"] = pattern or regex kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})"
class Form(Body): def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, media_type: str = "application/x-www-form-urlencoded", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class File(Form): def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, media_type: str = "multipart/form-data", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, )
class Depends: def __init__( self, dependency: Optional[Callable[..., Any]] = None, *, use_cache: bool = True ): self.dependency = dependency self.use_cache = use_cache
def __repr__(self) -> str: attr = getattr(self.dependency, "__name__", type(self.dependency).__name__) cache = "" if self.use_cache else ", use_cache=False" return f"{self.__class__.__name__}({attr}{cache})"
class Security(Depends): def __init__( self, dependency: Optional[Callable[..., Any]] = None, *, scopes: Optional[Sequence[str]] = None, use_cache: bool = True, ): super().__init__(dependency=dependency, use_cache=use_cache) self.scopes = scopes or []12from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401from starlette.requests import Request as Request # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748from typing import Any
from starlette.responses import FileResponse as FileResponse # noqafrom starlette.responses import HTMLResponse as HTMLResponse # noqafrom starlette.responses import JSONResponse as JSONResponse # noqafrom starlette.responses import PlainTextResponse as PlainTextResponse # noqafrom starlette.responses import RedirectResponse as RedirectResponse # noqafrom starlette.responses import Response as Response # noqafrom starlette.responses import StreamingResponse as StreamingResponse # noqa
try: import ujsonexcept ImportError: # pragma: nocover ujson = None # type: ignore
try: import orjsonexcept ImportError: # pragma: nocover orjson = None # type: ignore
class UJSONResponse(JSONResponse): """ JSON response using the high-performance ujson library to serialize data to JSON.
Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). """
def render(self, content: Any) -> bytes: assert ujson is not None, "ujson must be installed to use UJSONResponse" return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
class ORJSONResponse(JSONResponse): """ JSON response using the high-performance orjson library to serialize data to JSON.
Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). """
def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY )123456789101112131415from .api_key import APIKeyCookie as APIKeyCookiefrom .api_key import APIKeyHeader as APIKeyHeaderfrom .api_key import APIKeyQuery as APIKeyQueryfrom .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentialsfrom .http import HTTPBasic as HTTPBasicfrom .http import HTTPBasicCredentials as HTTPBasicCredentialsfrom .http import HTTPBearer as HTTPBearerfrom .http import HTTPDigest as HTTPDigestfrom .oauth2 import OAuth2 as OAuth2from .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearerfrom .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearerfrom .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestFormfrom .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrictfrom .oauth2 import SecurityScopes as SecurityScopesfrom .open_id_connect_url import OpenIdConnect as OpenIdConnect123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288from typing import Optional
from fastapi.openapi.models import APIKey, APIKeyInfrom fastapi.security.base import SecurityBasefrom starlette.exceptions import HTTPExceptionfrom starlette.requests import Requestfrom starlette.status import HTTP_403_FORBIDDENfrom typing_extensions import Annotated, Doc
class APIKeyBase(SecurityBase): @staticmethod def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]: if not api_key: if auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" ) return None return api_key
class APIKeyQuery(APIKeyBase): """ API key authentication using a query parameter.
This defines the name of the query parameter that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the query parameter automatically and provides it as the dependency result. But it doesn't define how to send that API key to the client.
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be a string containing the key value.
## Example
```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyQuery
app = FastAPI()
query_scheme = APIKeyQuery(name="api_key")
@app.get("/items/") async def read_items(api_key: str = Depends(query_scheme)): return {"api_key": api_key} ``` """
def __init__( self, *, name: Annotated[ str, Doc("Query parameter name."), ], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will automatically cancel the request and send the client an error.
If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be `None`.
This is useful when you want to have optional authentication.
It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a query parameter or in an HTTP Bearer token). """ ), ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.query}, # type: ignore[arg-type] name=name, description=description, ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error
async def __call__(self, request: Request) -> Optional[str]: api_key = request.query_params.get(self.model.name) return self.check_api_key(api_key, self.auto_error)
class APIKeyHeader(APIKeyBase): """ API key authentication using a header.
This defines the name of the header that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the header automatically and provides it as the dependency result. But it doesn't define how to send that key to the client.
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be a string containing the key value.
## Example
```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyHeader
app = FastAPI()
header_scheme = APIKeyHeader(name="x-key")
@app.get("/items/") async def read_items(key: str = Depends(header_scheme)): return {"key": key} ``` """
def __init__( self, *, name: Annotated[str, Doc("Header name.")], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the header is not provided, `APIKeyHeader` will automatically cancel the request and send the client an error.
If `auto_error` is set to `False`, when the header is not available, instead of erroring out, the dependency result will be `None`.
This is useful when you want to have optional authentication.
It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a header or in an HTTP Bearer token). """ ), ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.header}, # type: ignore[arg-type] name=name, description=description, ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error
async def __call__(self, request: Request) -> Optional[str]: api_key = request.headers.get(self.model.name) return self.check_api_key(api_key, self.auto_error)
class APIKeyCookie(APIKeyBase): """ API key authentication using a cookie.
This defines the name of the cookie that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the cookie automatically and provides it as the dependency result. But it doesn't define how to set that cookie.
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be a string containing the key value.
## Example
```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyCookie
app = FastAPI()
cookie_scheme = APIKeyCookie(name="session")
@app.get("/items/") async def read_items(session: str = Depends(cookie_scheme)): return {"session": session} ``` """
def __init__( self, *, name: Annotated[str, Doc("Cookie name.")], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description.
It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the cookie is not provided, `APIKeyCookie` will automatically cancel the request and send the client an error.
If `auto_error` is set to `False`, when the cookie is not available, instead of erroring out, the dependency result will be `None`.
This is useful when you want to have optional authentication.
It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a cookie or in an HTTP Bearer token). """ ), ] = True, ): self.model: APIKey = APIKey( **{"in": APIKeyIn.cookie}, # type: ignore[arg-type] name=name, description=description, ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error
async def __call__(self, request: Request) -> Optional[str]: api_key = request.cookies.get(self.model.name) return self.check_api_key(api_key, self.auto_error)lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/METADATAAdded+187
lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/RECORDAdded+11
lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/WHEELAdded+4
lib/python3.12/site-packages/cloudpickle-3.1.2.dist-info/licenses/LICENSEAdded+32
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/METADATAAdded+169
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/RECORDAdded+101
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/REQUESTEDAdded
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/WHEELAdded+5
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/licenses/LICENSEAdded+201
lib/python3.12/site-packages/compressed_tensors-0.9.3.dist-info/top_level.txtAdded+1
lib/python3.12/site-packages/fastapi/__init__.pyAdded+25
lib/python3.12/site-packages/fastapi/__main__.pyAdded+3
lib/python3.12/site-packages/fastapi/__pycache__/param_functions.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/_compat.pyAdded+659
lib/python3.12/site-packages/fastapi/applications.pyAdded
lib/python3.12/site-packages/fastapi/background.pyAdded+59
lib/python3.12/site-packages/fastapi/cli.pyAdded+13
lib/python3.12/site-packages/fastapi/concurrency.pyAdded+39
lib/python3.12/site-packages/fastapi/datastructures.pyAdded+204
lib/python3.12/site-packages/fastapi/encoders.pyAdded+343
lib/python3.12/site-packages/fastapi/exception_handlers.pyAdded+34
lib/python3.12/site-packages/fastapi/exceptions.pyAdded+176
lib/python3.12/site-packages/fastapi/logger.pyAdded+3
lib/python3.12/site-packages/fastapi/openapi/__init__.pyAdded
lib/python3.12/site-packages/fastapi/openapi/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/openapi/__pycache__/constants.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/openapi/__pycache__/docs.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/openapi/__pycache__/models.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/openapi/__pycache__/utils.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/openapi/constants.pyAdded+3
lib/python3.12/site-packages/fastapi/openapi/docs.pyAdded+344
lib/python3.12/site-packages/fastapi/openapi/models.pyAdded+445
lib/python3.12/site-packages/fastapi/openapi/utils.pyAdded+569
lib/python3.12/site-packages/fastapi/param_functions.pyAdded+2360
lib/python3.12/site-packages/fastapi/params.pyAdded+786
lib/python3.12/site-packages/fastapi/py.typedAdded
lib/python3.12/site-packages/fastapi/requests.pyAdded+2
lib/python3.12/site-packages/fastapi/responses.pyAdded+48
lib/python3.12/site-packages/fastapi/routing.pyAdded
lib/python3.12/site-packages/fastapi/security/__init__.pyAdded+15
lib/python3.12/site-packages/fastapi/security/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/api_key.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/base.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/http.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/oauth2.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/open_id_connect_url.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/__pycache__/utils.cpython-312.pycAdded
lib/python3.12/site-packages/fastapi/security/api_key.pyAdded+288