diff --git a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/INSTALLER b/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/LICENSE.rst b/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/LICENSE.rst deleted file mode 100644 index c37cae4..0000000 --- a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/LICENSE.rst +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2007 Pallets - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. 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. - -3. Neither the name of the copyright holder 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 NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/METADATA b/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/METADATA deleted file mode 100644 index f54bb5c..0000000 --- a/server/venv/Lib/site-packages/Jinja2-3.1.2.dist-info/METADATA +++ /dev/null @@ -1,113 +0,0 @@ -Metadata-Version: 2.1 -Name: Jinja2 -Version: 3.1.2 -Summary: A very fast and expressive template engine. -Home-page: https://palletsprojects.com/p/jinja/ -Author: Armin Ronacher -Author-email: armin.ronacher@active-4.com -Maintainer: Pallets -Maintainer-email: contact@palletsprojects.com -License: BSD-3-Clause -Project-URL: Donate, https://palletsprojects.com/donate -Project-URL: Documentation, https://jinja.palletsprojects.com/ -Project-URL: Changes, https://jinja.palletsprojects.com/changes/ -Project-URL: Source Code, https://github.com/pallets/jinja/ -Project-URL: Issue Tracker, https://github.com/pallets/jinja/issues/ -Project-URL: Twitter, https://twitter.com/PalletsTeam -Project-URL: Chat, https://discord.gg/pallets -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Environment :: Web Environment -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: BSD License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content -Classifier: Topic :: Text Processing :: Markup :: HTML -Requires-Python: >=3.7 -Description-Content-Type: text/x-rst -License-File: LICENSE.rst -Requires-Dist: MarkupSafe (>=2.0) -Provides-Extra: i18n -Requires-Dist: Babel (>=2.7) ; extra == 'i18n' - -Jinja -===== - -Jinja is a fast, expressive, extensible templating engine. Special -placeholders in the template allow writing code similar to Python -syntax. Then the template is passed data to render the final document. - -It includes: - -- Template inheritance and inclusion. -- Define and import macros within templates. -- HTML templates can use autoescaping to prevent XSS from untrusted - user input. -- A sandboxed environment can safely render untrusted templates. -- AsyncIO support for generating templates and calling async - functions. -- I18N support with Babel. -- Templates are compiled to optimized Python code just-in-time and - cached, or can be compiled ahead-of-time. -- Exceptions point to the correct line in templates to make debugging - easier. -- Extensible filters, tests, functions, and even syntax. - -Jinja's philosophy is that while application logic belongs in Python if -possible, it shouldn't make the template designer's job difficult by -restricting functionality too much. - - -Installing ----------- - -Install and update using `pip`_: - -.. code-block:: text - - $ pip install -U Jinja2 - -.. _pip: https://pip.pypa.io/en/stable/getting-started/ - - -In A Nutshell -------------- - -.. code-block:: jinja - - {% extends "base.html" %} - {% block title %}Members{% endblock %} - {% block content %} -
- The Real First Universal Charset Detector
-
-
-
-
-
-
-
-
-
-
- Featured Packages
-
-
-
-
-
-
-
- In other language (unofficial port - by the community)
-
-
-
-
- >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< -
- -This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. - -| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | -|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:| -| `Fast` | ❌ | ✅ | ✅ | -| `Universal**` | ❌ | ✅ | ❌ | -| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | -| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | -| `License` | LGPL-2.1- -
- -*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*- FastAPI framework, high performance, easy to learn, fast to code, ready for production -
- - ---- - -**Documentation**: https://fastapi.tiangolo.com - -**Source Code**: https://github.com/tiangolo/fastapi - ---- - -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. - -The key features are: - -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. - -* estimation based on tests on an internal development team, building production applications. - -## Sponsors - - - - - - - - - - - - - - - - - - - -Other sponsors - -## Opinions - -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" - -async def
...uvicorn main:app --reload
...email_validator
- for email validation.
-* pydantic-settings
- for settings management.
-* pydantic-extra-types
- for extra types to be used with Pydantic.
-
-Used by Starlette:
-
-* httpx
- Required if you want to use the `TestClient`.
-* jinja2
- Required if you want to use the default template configuration.
-* python-multipart
- Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous
- Required for `SessionMiddleware` support.
-* pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson
- Required if you want to use `UJSONResponse`.
-
-Used by FastAPI / Starlette:
-
-* uvicorn
- for the server that loads and serves your application.
-* orjson
- Required if you want to use `ORJSONResponse`.
-
-You can install all of these with `pip install "fastapi[all]"`.
-
-## License
-
-This project is licensed under the terms of the MIT license.
diff --git a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/RECORD b/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/RECORD
deleted file mode 100644
index 7aa86a0..0000000
--- a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/RECORD
+++ /dev/null
@@ -1,93 +0,0 @@
-fastapi-0.104.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
-fastapi-0.104.0.dist-info/METADATA,sha256=CkzeBpixDOSeV0EHeSYTRlEY06F6nJwCcgTBbBTqcyY,24298
-fastapi-0.104.0.dist-info/RECORD,,
-fastapi-0.104.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-fastapi-0.104.0.dist-info/WHEEL,sha256=9QBuHhg6FNW7lppboF2vKVbCGTVzsFykgRQjjlajrhA,87
-fastapi-0.104.0.dist-info/licenses/LICENSE,sha256=Tsif_IFIW5f-xYSy1KlhAy7v_oNEU4lP2cEnSQbMdE4,1086
-fastapi/__init__.py,sha256=gn98glQhIF340JPgqEZxbeyUUHwWya-Wdin8FALRQc0,1081
-fastapi/__pycache__/__init__.cpython-311.pyc,,
-fastapi/__pycache__/_compat.cpython-311.pyc,,
-fastapi/__pycache__/applications.cpython-311.pyc,,
-fastapi/__pycache__/background.cpython-311.pyc,,
-fastapi/__pycache__/concurrency.cpython-311.pyc,,
-fastapi/__pycache__/datastructures.cpython-311.pyc,,
-fastapi/__pycache__/encoders.cpython-311.pyc,,
-fastapi/__pycache__/exception_handlers.cpython-311.pyc,,
-fastapi/__pycache__/exceptions.cpython-311.pyc,,
-fastapi/__pycache__/logger.cpython-311.pyc,,
-fastapi/__pycache__/param_functions.cpython-311.pyc,,
-fastapi/__pycache__/params.cpython-311.pyc,,
-fastapi/__pycache__/requests.cpython-311.pyc,,
-fastapi/__pycache__/responses.cpython-311.pyc,,
-fastapi/__pycache__/routing.cpython-311.pyc,,
-fastapi/__pycache__/staticfiles.cpython-311.pyc,,
-fastapi/__pycache__/templating.cpython-311.pyc,,
-fastapi/__pycache__/testclient.cpython-311.pyc,,
-fastapi/__pycache__/types.cpython-311.pyc,,
-fastapi/__pycache__/utils.cpython-311.pyc,,
-fastapi/__pycache__/websockets.cpython-311.pyc,,
-fastapi/_compat.py,sha256=xAFxZVkeuyOGlAHgCU_tmCtSLZjGkXvUElaeyoKoVrk,22796
-fastapi/applications.py,sha256=0x_D9p1AwI8EoBWgL_AsG0Qw8bp6TSZiDKqoAXR5W-w,179291
-fastapi/background.py,sha256=F1tsrJKfDZaRchNgF9ykB2PcRaPBJTbL4htN45TJAIc,1799
-fastapi/concurrency.py,sha256=NAK9SMlTCOALLjTAR6KzWUDEkVj7_EyNRz0-lDVW_W8,1467
-fastapi/datastructures.py,sha256=FF1s2g6cAQ5XxlNToB3scgV94Zf3DjdzcaI7ToaTrmg,5797
-fastapi/dependencies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-fastapi/dependencies/__pycache__/__init__.cpython-311.pyc,,
-fastapi/dependencies/__pycache__/models.cpython-311.pyc,,
-fastapi/dependencies/__pycache__/utils.cpython-311.pyc,,
-fastapi/dependencies/models.py,sha256=-n-YCxzgVBkurQi49qOTooT71v_oeAhHJ-qQFonxh5o,2494
-fastapi/dependencies/utils.py,sha256=DjRdd_NVdXh_jDYKTRjUIXkwkLD0WE4oFXQC4peMr2c,29915
-fastapi/encoders.py,sha256=90lbmIW8NZjpPVzbgKhpY49B7TFqa7hrdQDQa70SM9U,11024
-fastapi/exception_handlers.py,sha256=MBrIOA-ugjJDivIi4rSsUJBdTsjuzN76q4yh0q1COKw,1332
-fastapi/exceptions.py,sha256=SQsPxq-QYBZUhq6L4K3B3W7gaSD3Gub2f17erStRagY,5000
-fastapi/logger.py,sha256=I9NNi3ov8AcqbsbC9wl1X-hdItKgYt2XTrx1f99Zpl4,54
-fastapi/middleware/__init__.py,sha256=oQDxiFVcc1fYJUOIFvphnK7pTT5kktmfL32QXpBFvvo,58
-fastapi/middleware/__pycache__/__init__.cpython-311.pyc,,
-fastapi/middleware/__pycache__/asyncexitstack.cpython-311.pyc,,
-fastapi/middleware/__pycache__/cors.cpython-311.pyc,,
-fastapi/middleware/__pycache__/gzip.cpython-311.pyc,,
-fastapi/middleware/__pycache__/httpsredirect.cpython-311.pyc,,
-fastapi/middleware/__pycache__/trustedhost.cpython-311.pyc,,
-fastapi/middleware/__pycache__/wsgi.cpython-311.pyc,,
-fastapi/middleware/asyncexitstack.py,sha256=LvMyVI1QdmWNWYPZqx295VFavssUfVpUsonPOsMWz1E,1035
-fastapi/middleware/cors.py,sha256=ynwjWQZoc_vbhzZ3_ZXceoaSrslHFHPdoM52rXr0WUU,79
-fastapi/middleware/gzip.py,sha256=xM5PcsH8QlAimZw4VDvcmTnqQamslThsfe3CVN2voa0,79
-fastapi/middleware/httpsredirect.py,sha256=rL8eXMnmLijwVkH7_400zHri1AekfeBd6D6qs8ix950,115
-fastapi/middleware/trustedhost.py,sha256=eE5XGRxGa7c5zPnMJDGp3BxaL25k5iVQlhnv-Pk0Pss,109
-fastapi/middleware/wsgi.py,sha256=Z3Ue-7wni4lUZMvH3G9ek__acgYdJstbnpZX_HQAboY,79
-fastapi/openapi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-fastapi/openapi/__pycache__/__init__.cpython-311.pyc,,
-fastapi/openapi/__pycache__/constants.cpython-311.pyc,,
-fastapi/openapi/__pycache__/docs.cpython-311.pyc,,
-fastapi/openapi/__pycache__/models.cpython-311.pyc,,
-fastapi/openapi/__pycache__/utils.cpython-311.pyc,,
-fastapi/openapi/constants.py,sha256=adGzmis1L1HJRTE3kJ5fmHS_Noq6tIY6pWv_SFzoFDU,153
-fastapi/openapi/docs.py,sha256=gnnivCh7N0AOTVLpGrDOlo4P4h1CrbU6vcqeNhvZGkI,10379
-fastapi/openapi/models.py,sha256=DEmsWA-9sNqv2H4YneZUW86r1nMwD920EiTvan5kndI,17763
-fastapi/openapi/utils.py,sha256=PUuz_ISarHVPBRyIgfyHz8uwH0eEsDY3rJUfW__I9GI,22303
-fastapi/param_functions.py,sha256=VWEsJbkH8lJZgcJ6fI6uzquui1kgHrDv1i_wXM7cW3M,63896
-fastapi/params.py,sha256=LzjihAvODd3w7-GddraUyVtH1xfwR9smIoQn-Z_g4mg,27807
-fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
-fastapi/requests.py,sha256=zayepKFcienBllv3snmWI20Gk0oHNVLU4DDhqXBb4LU,142
-fastapi/responses.py,sha256=QNQQlwpKhQoIPZTTWkpc9d_QGeGZ_aVQPaDV3nQ8m7c,1761
-fastapi/routing.py,sha256=wtZXvIphGDMUBkBkZHMWgiiiQZX28HXNvPxxT0HWwXA,172396
-fastapi/security/__init__.py,sha256=bO8pNmxqVRXUjfl2mOKiVZLn0FpBQ61VUYVjmppnbJw,881
-fastapi/security/__pycache__/__init__.cpython-311.pyc,,
-fastapi/security/__pycache__/api_key.cpython-311.pyc,,
-fastapi/security/__pycache__/base.cpython-311.pyc,,
-fastapi/security/__pycache__/http.cpython-311.pyc,,
-fastapi/security/__pycache__/oauth2.cpython-311.pyc,,
-fastapi/security/__pycache__/open_id_connect_url.cpython-311.pyc,,
-fastapi/security/__pycache__/utils.cpython-311.pyc,,
-fastapi/security/api_key.py,sha256=bcZbUzTqeR_CI_LXuJdDq1qL322kmhgy5ApOCqgGDi4,9399
-fastapi/security/base.py,sha256=dl4pvbC-RxjfbWgPtCWd8MVU-7CB2SZ22rJDXVCXO6c,141
-fastapi/security/http.py,sha256=RVnZNavpUNHr6wguijiM3uNKt-b4i_bXgdT_JInuVZY,13523
-fastapi/security/oauth2.py,sha256=sjJgO5WL7j0cxnigzfF1zIIR1hgK_YSvh05B8KtxE94,21636
-fastapi/security/open_id_connect_url.py,sha256=Mb8wFxrRh4CrsFW0RcjBEQLASPHGDtZRP6c2dCrspAg,2753
-fastapi/security/utils.py,sha256=bd8T0YM7UQD5ATKucr1bNtAvz_Y3__dVNAv5UebiPvc,293
-fastapi/staticfiles.py,sha256=iirGIt3sdY2QZXd36ijs3Cj-T0FuGFda3cd90kM9Ikw,69
-fastapi/templating.py,sha256=4zsuTWgcjcEainMJFAlW6-gnslm6AgOS1SiiDWfmQxk,76
-fastapi/testclient.py,sha256=nBvaAmX66YldReJNZXPOk1sfuo2Q6hs8bOvIaCep6LQ,66
-fastapi/types.py,sha256=WZJ1jvm1MCwIrxxRYxKwtXS9HqcGk0RnCbLzrMZh-lI,428
-fastapi/utils.py,sha256=_vUwlqa4dq8M0Rl3Pro051teIccx36Z4hgecGH8F_oA,8179
-fastapi/websockets.py,sha256=419uncYObEKZG0YcrXscfQQYLSWoE10jqxVMetGdR98,222
diff --git a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/REQUESTED b/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/REQUESTED
deleted file mode 100644
index e69de29..0000000
diff --git a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/WHEEL b/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/WHEEL
deleted file mode 100644
index ba1a8af..0000000
--- a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/WHEEL
+++ /dev/null
@@ -1,4 +0,0 @@
-Wheel-Version: 1.0
-Generator: hatchling 1.18.0
-Root-Is-Purelib: true
-Tag: py3-none-any
diff --git a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/licenses/LICENSE b/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/licenses/LICENSE
deleted file mode 100644
index 3e92463..0000000
--- a/server/venv/Lib/site-packages/fastapi-0.104.0.dist-info/licenses/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2018 Sebastián Ramírez
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/server/venv/Lib/site-packages/fastapi/__init__.py b/server/venv/Lib/site-packages/fastapi/__init__.py
deleted file mode 100644
index 4fdb155..0000000
--- a/server/venv/Lib/site-packages/fastapi/__init__.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
-
-__version__ = "0.104.0"
-
-from starlette import status as status
-
-from .applications import FastAPI as FastAPI
-from .background import BackgroundTasks as BackgroundTasks
-from .datastructures import UploadFile as UploadFile
-from .exceptions import HTTPException as HTTPException
-from .exceptions import WebSocketException as WebSocketException
-from .param_functions import Body as Body
-from .param_functions import Cookie as Cookie
-from .param_functions import Depends as Depends
-from .param_functions import File as File
-from .param_functions import Form as Form
-from .param_functions import Header as Header
-from .param_functions import Path as Path
-from .param_functions import Query as Query
-from .param_functions import Security as Security
-from .requests import Request as Request
-from .responses import Response as Response
-from .routing import APIRouter as APIRouter
-from .websockets import WebSocket as WebSocket
-from .websockets import WebSocketDisconnect as WebSocketDisconnect
diff --git a/server/venv/Lib/site-packages/fastapi/_compat.py b/server/venv/Lib/site-packages/fastapi/_compat.py
deleted file mode 100644
index a4b305d..0000000
--- a/server/venv/Lib/site-packages/fastapi/_compat.py
+++ /dev/null
@@ -1,629 +0,0 @@
-from collections import deque
-from copy import copy
-from dataclasses import dataclass, is_dataclass
-from enum import Enum
-from typing import (
- Any,
- Callable,
- Deque,
- Dict,
- FrozenSet,
- List,
- Mapping,
- Sequence,
- Set,
- Tuple,
- Type,
- Union,
-)
-
-from fastapi.exceptions import RequestErrorModel
-from fastapi.types import IncEx, ModelNameMap, UnionType
-from pydantic import BaseModel, create_model
-from pydantic.version import VERSION as PYDANTIC_VERSION
-from starlette.datastructures import UploadFile
-from typing_extensions import Annotated, Literal, get_args, get_origin
-
-PYDANTIC_V2 = PYDANTIC_VERSION.startswith("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())
-
-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
- )
-
- Required = 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(), 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:
- return type(field_info).from_annotation(annotation)
-
- 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()[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
-
-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
- )
- from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
- Required as Required, # noqa: F401
- )
- 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 _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:
- 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)
- )
diff --git a/server/venv/Lib/site-packages/fastapi/applications.py b/server/venv/Lib/site-packages/fastapi/applications.py
deleted file mode 100644
index 46b7ae8..0000000
--- a/server/venv/Lib/site-packages/fastapi/applications.py
+++ /dev/null
@@ -1,4646 +0,0 @@
-from enum import Enum
-from typing import (
- Any,
- Awaitable,
- Callable,
- Coroutine,
- Dict,
- List,
- Optional,
- Sequence,
- Type,
- TypeVar,
- Union,
-)
-
-from fastapi import routing
-from fastapi.datastructures import Default, DefaultPlaceholder
-from fastapi.exception_handlers import (
- http_exception_handler,
- request_validation_exception_handler,
- websocket_request_validation_exception_handler,
-)
-from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
-from fastapi.logger import logger
-from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware
-from fastapi.openapi.docs import (
- get_redoc_html,
- get_swagger_ui_html,
- get_swagger_ui_oauth2_redirect_html,
-)
-from fastapi.openapi.utils import get_openapi
-from fastapi.params import Depends
-from fastapi.types import DecoratedCallable, IncEx
-from fastapi.utils import generate_unique_id
-from starlette.applications import Starlette
-from starlette.datastructures import State
-from starlette.exceptions import HTTPException
-from starlette.middleware import Middleware
-from starlette.middleware.base import BaseHTTPMiddleware
-from starlette.middleware.errors import ServerErrorMiddleware
-from starlette.middleware.exceptions import ExceptionMiddleware
-from starlette.requests import Request
-from starlette.responses import HTMLResponse, JSONResponse, Response
-from starlette.routing import BaseRoute
-from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
-from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined]
-
-AppType = TypeVar("AppType", bound="FastAPI")
-
-
-class FastAPI(Starlette):
- """
- `FastAPI` app class, the main entrypoint to use FastAPI.
-
- Read more in the
- [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
- ```
- """
-
- def __init__(
- self: AppType,
- *,
- debug: Annotated[
- bool,
- Doc(
- """
- Boolean indicating if debug tracebacks should be returned on server
- errors.
-
- Read more in the
- [Starlette docs for Applications](https://www.starlette.io/applications/#instantiating-the-application).
- """
- ),
- ] = False,
- routes: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- **Note**: you probably shouldn't use this parameter, it is inherited
- from Starlette and supported for compatibility.
-
- In FastAPI, you normally would use the *path operation* decorators,
- like:
-
- * `app.get()`
- * `app.post()`
- * etc.
-
- ---
-
- A list of routes to serve incoming HTTP and WebSocket requests.
- """
- ),
- deprecated(
- """
- You normally wouldn't use this parameter with FastAPI, it is inherited
- from Starlette and supported for compatibility.
-
- In FastAPI, you normally would use the *path operation methods*,
- like `app.get()`, `app.post()`, etc.
- """
- ),
- ] = None,
- title: Annotated[
- str,
- Doc(
- """
- The title of the API.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(title="ChimichangApp")
- ```
- """
- ),
- ] = "FastAPI",
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A short summary of the API.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(summary="Deadpond's favorite app. Nuff said.")
- ```
- """
- ),
- ] = None,
- description: Annotated[
- str,
- Doc(
- '''
- A description of the API. Supports Markdown (using
- [CommonMark syntax](https://commonmark.org/)).
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(
- description="""
- ChimichangApp API helps you do awesome stuff. 🚀
-
- ## Items
-
- You can **read items**.
-
- ## Users
-
- You will be able to:
-
- * **Create users** (_not implemented_).
- * **Read users** (_not implemented_).
-
- """
- )
- ```
- '''
- ),
- ] = "",
- version: Annotated[
- str,
- Doc(
- """
- The version of the API.
-
- **Note** This is the version of your application, not the version of
- the OpenAPI specification nor the version of FastAPI being used.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(version="0.0.1")
- ```
- """
- ),
- ] = "0.1.0",
- openapi_url: Annotated[
- Optional[str],
- Doc(
- """
- The URL where the OpenAPI schema will be served from.
-
- If you set it to `None`, no OpenAPI schema will be served publicly, and
- the default automatic endpoints `/docs` and `/redoc` will also be
- disabled.
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(openapi_url="/api/v1/openapi.json")
- ```
- """
- ),
- ] = "/openapi.json",
- openapi_tags: Annotated[
- Optional[List[Dict[str, Any]]],
- Doc(
- """
- A list of tags used by OpenAPI, these are the same `tags` you can set
- in the *path operations*, like:
-
- * `@app.get("/users/", tags=["users"])`
- * `@app.get("/items/", tags=["items"])`
-
- The order of the tags can be used to specify the order shown in
- tools like Swagger UI, used in the automatic path `/docs`.
-
- It's not required to specify all the tags used.
-
- The tags that are not declared MAY be organized randomly or based
- on the tools' logic. Each tag name in the list MUST be unique.
-
- The value of each item is a `dict` containing:
-
- * `name`: The name of the tag.
- * `description`: A short description of the tag.
- [CommonMark syntax](https://commonmark.org/) MAY be used for rich
- text representation.
- * `externalDocs`: Additional external documentation for this tag. If
- provided, it would contain a `dict` with:
- * `description`: A short description of the target documentation.
- [CommonMark syntax](https://commonmark.org/) MAY be used for
- rich text representation.
- * `url`: The URL for the target documentation. Value MUST be in
- the form of a URL.
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- tags_metadata = [
- {
- "name": "users",
- "description": "Operations with users. The **login** logic is also here.",
- },
- {
- "name": "items",
- "description": "Manage items. So _fancy_ they have their own docs.",
- "externalDocs": {
- "description": "Items external docs",
- "url": "https://fastapi.tiangolo.com/",
- },
- },
- ]
-
- app = FastAPI(openapi_tags=tags_metadata)
- ```
- """
- ),
- ] = None,
- servers: Annotated[
- Optional[List[Dict[str, Union[str, Any]]]],
- Doc(
- """
- A `list` of `dict`s with connectivity information to a target server.
-
- You would use it, for example, if your application is served from
- different domains and you want to use the same Swagger UI in the
- browser to interact with each of them (instead of having multiple
- browser tabs open). Or if you want to leave fixed the possible URLs.
-
- If the servers `list` is not provided, or is an empty `list`, the
- default value would be a a `dict` with a `url` value of `/`.
-
- Each item in the `list` is a `dict` containing:
-
- * `url`: A URL to the target host. This URL supports Server Variables
- and MAY be relative, to indicate that the host location is relative
- to the location where the OpenAPI document is being served. Variable
- substitutions will be made when a variable is named in `{`brackets`}`.
- * `description`: An optional string describing the host designated by
- the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for
- rich text representation.
- * `variables`: A `dict` between a variable name and its value. The value
- is used for substitution in the server's URL template.
-
- Read more in the
- [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(
- servers=[
- {"url": "https://stag.example.com", "description": "Staging environment"},
- {"url": "https://prod.example.com", "description": "Production environment"},
- ]
- )
- ```
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of global dependencies, they will be applied to each
- *path operation*, including in sub-routers.
-
- Read more about it in the
- [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).
-
- **Example**
-
- ```python
- from fastapi import Depends, FastAPI
-
- from .dependencies import func_dep_1, func_dep_2
-
- app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
- ```
- """
- ),
- ] = None,
- default_response_class: Annotated[
- Type[Response],
- Doc(
- """
- The default response class to be used.
-
- Read more in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
- from fastapi.responses import ORJSONResponse
-
- app = FastAPI(default_response_class=ORJSONResponse)
- ```
- """
- ),
- ] = Default(JSONResponse),
- redirect_slashes: Annotated[
- bool,
- Doc(
- """
- Whether to detect and redirect slashes in URLs when the client doesn't
- use the same format.
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(redirect_slashes=True) # the default
-
- @app.get("/items/")
- async def read_items():
- return [{"item_id": "Foo"}]
- ```
-
- With this app, if a client goes to `/items` (without a trailing slash),
- they will be automatically redirected with an HTTP status code of 307
- to `/items/`.
- """
- ),
- ] = True,
- docs_url: Annotated[
- Optional[str],
- Doc(
- """
- The path to the automatic interactive API documentation.
- It is handled in the browser by Swagger UI.
-
- The default URL is `/docs`. You can disable it by setting it to `None`.
-
- If `openapi_url` is set to `None`, this will be automatically disabled.
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(docs_url="/documentation", redoc_url=None)
- ```
- """
- ),
- ] = "/docs",
- redoc_url: Annotated[
- Optional[str],
- Doc(
- """
- The path to the alternative automatic interactive API documentation
- provided by ReDoc.
-
- The default URL is `/redoc`. You can disable it by setting it to `None`.
-
- If `openapi_url` is set to `None`, this will be automatically disabled.
-
- Read more in the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")
- ```
- """
- ),
- ] = "/redoc",
- swagger_ui_oauth2_redirect_url: Annotated[
- Optional[str],
- Doc(
- """
- The OAuth2 redirect endpoint for the Swagger UI.
-
- By default it is `/docs/oauth2-redirect`.
-
- This is only used if you use OAuth2 (with the "Authorize" button)
- with Swagger UI.
- """
- ),
- ] = "/docs/oauth2-redirect",
- swagger_ui_init_oauth: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
-
- Read more about the available configuration options in the
- [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).
- """
- ),
- ] = None,
- middleware: Annotated[
- Optional[Sequence[Middleware]],
- Doc(
- """
- List of middleware to be added when creating the application.
-
- In FastAPI you would normally do this with `app.add_middleware()`
- instead.
-
- Read more in the
- [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
- """
- ),
- ] = None,
- exception_handlers: Annotated[
- Optional[
- Dict[
- Union[int, Type[Exception]],
- Callable[[Request, Any], Coroutine[Any, Any, Response]],
- ]
- ],
- Doc(
- """
- A dictionary with handlers for exceptions.
-
- In FastAPI, you would normally use the decorator
- `@app.exception_handler()`.
-
- Read more in the
- [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
- """
- ),
- ] = None,
- on_startup: Annotated[
- Optional[Sequence[Callable[[], Any]]],
- Doc(
- """
- A list of startup event handler functions.
-
- You should instead use the `lifespan` handlers.
-
- Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
- """
- ),
- ] = None,
- on_shutdown: Annotated[
- Optional[Sequence[Callable[[], Any]]],
- Doc(
- """
- A list of shutdown event handler functions.
-
- You should instead use the `lifespan` handlers.
-
- Read more in the
- [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
- """
- ),
- ] = None,
- lifespan: Annotated[
- Optional[Lifespan[AppType]],
- Doc(
- """
- A `Lifespan` context manager handler. This replaces `startup` and
- `shutdown` functions with a single context manager.
-
- Read more in the
- [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
- """
- ),
- ] = None,
- terms_of_service: Annotated[
- Optional[str],
- Doc(
- """
- A URL to the Terms of Service for your API.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more at the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- app = FastAPI(terms_of_service="http://example.com/terms/")
- ```
- """
- ),
- ] = None,
- contact: Annotated[
- Optional[Dict[str, Union[str, Any]]],
- Doc(
- """
- A dictionary with the contact information for the exposed API.
-
- It can contain several fields.
-
- * `name`: (`str`) The name of the contact person/organization.
- * `url`: (`str`) A URL pointing to the contact information. MUST be in
- the format of a URL.
- * `email`: (`str`) The email address of the contact person/organization.
- MUST be in the format of an email address.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more at the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- app = FastAPI(
- contact={
- "name": "Deadpoolio the Amazing",
- "url": "http://x-force.example.com/contact/",
- "email": "dp@x-force.example.com",
- }
- )
- ```
- """
- ),
- ] = None,
- license_info: Annotated[
- Optional[Dict[str, Union[str, Any]]],
- Doc(
- """
- A dictionary with the license information for the exposed API.
-
- It can contain several fields.
-
- * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The
- license name used for the API.
- * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression
- for the API. The `identifier` field is mutually exclusive of the `url`
- field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
- * `url`: (`str`) A URL to the license used for the API. This MUST be
- the format of a URL.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more at the
- [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
-
- **Example**
-
- ```python
- app = FastAPI(
- license_info={
- "name": "Apache 2.0",
- "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
- }
- )
- ```
- """
- ),
- ] = None,
- openapi_prefix: Annotated[
- str,
- Doc(
- """
- A URL prefix for the OpenAPI URL.
- """
- ),
- deprecated(
- """
- "openapi_prefix" has been deprecated in favor of "root_path", which
- follows more closely the ASGI standard, is simpler, and more
- automatic.
- """
- ),
- ] = "",
- root_path: Annotated[
- str,
- Doc(
- """
- A path prefix handled by a proxy that is not seen by the application
- but is seen by external clients, which affects things like Swagger UI.
-
- Read more about it at the
- [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(root_path="/api/v1")
- ```
- """
- ),
- ] = "",
- root_path_in_servers: Annotated[
- bool,
- Doc(
- """
- To disable automatically generating the URLs in the `servers` field
- in the autogenerated OpenAPI using the `root_path`.
-
- Read more about it in the
- [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root_path).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI(root_path_in_servers=False)
- ```
- """
- ),
- ] = True,
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses to be shown in OpenAPI.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
-
- And in the
- [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- OpenAPI callbacks that should apply to all *path operations*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- webhooks: Annotated[
- Optional[routing.APIRouter],
- Doc(
- """
- Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't
- depend on specific *path operations*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.
-
- Read more about it in the
- [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark all *path operations* as deprecated. You probably don't need it,
- but it's available.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- To include (or not) all the *path operations* in the generated OpenAPI.
- You probably don't need it, but it's available.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- swagger_ui_parameters: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Parameters to configure Swagger UI, the autogenerated interactive API
- documentation (by default at `/docs`).
-
- Read more about it in the
- [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- separate_input_output_schemas: Annotated[
- bool,
- Doc(
- """
- Whether to generate separate OpenAPI schemas for request body and
- response body when the results would be more precise.
-
- This is particularly useful when automatically generating clients.
-
- For example, if you have a model like:
-
- ```python
- from pydantic import BaseModel
-
- class Item(BaseModel):
- name: str
- tags: list[str] = []
- ```
-
- When `Item` is used for input, a request body, `tags` is not required,
- the client doesn't have to provide it.
-
- But when using `Item` for output, for a response body, `tags` is always
- available because it has a default value, even if it's just an empty
- list. So, the client should be able to always expect it.
-
- In this case, there would be two different schemas, one for input and
- another one for output.
- """
- ),
- ] = True,
- **extra: Annotated[
- Any,
- Doc(
- """
- Extra keyword arguments to be stored in the app, not used by FastAPI
- anywhere.
- """
- ),
- ],
- ) -> None:
- self.debug = debug
- self.title = title
- self.summary = summary
- self.description = description
- self.version = version
- self.terms_of_service = terms_of_service
- self.contact = contact
- self.license_info = license_info
- self.openapi_url = openapi_url
- self.openapi_tags = openapi_tags
- self.root_path_in_servers = root_path_in_servers
- self.docs_url = docs_url
- self.redoc_url = redoc_url
- self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
- self.swagger_ui_init_oauth = swagger_ui_init_oauth
- self.swagger_ui_parameters = swagger_ui_parameters
- self.servers = servers or []
- self.separate_input_output_schemas = separate_input_output_schemas
- self.extra = extra
- self.openapi_version: Annotated[
- str,
- Doc(
- """
- The version string of OpenAPI.
-
- FastAPI will generate OpenAPI version 3.1.0, and will output that as
- the OpenAPI version. But some tools, even though they might be
- compatible with OpenAPI 3.1.0, might not recognize it as a valid.
-
- So you could override this value to trick those tools into using
- the generated OpenAPI. Have in mind that this is a hack. But if you
- avoid using features added in OpenAPI 3.1.0, it might work for your
- use case.
-
- This is not passed as a parameter to the `FastAPI` class to avoid
- giving the false idea that FastAPI would generate a different OpenAPI
- schema. It is only available as an attribute.
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
-
- app.openapi_version = "3.0.2"
- ```
- """
- ),
- ] = "3.1.0"
- self.openapi_schema: Optional[Dict[str, Any]] = None
- if self.openapi_url:
- assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
- assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
- # TODO: remove when discarding the openapi_prefix parameter
- if openapi_prefix:
- logger.warning(
- '"openapi_prefix" has been deprecated in favor of "root_path", which '
- "follows more closely the ASGI standard, is simpler, and more "
- "automatic. Check the docs at "
- "https://fastapi.tiangolo.com/advanced/sub-applications/"
- )
- self.webhooks: Annotated[
- routing.APIRouter,
- Doc(
- """
- The `app.webhooks` attribute is an `APIRouter` with the *path
- operations* that will be used just for documentation of webhooks.
-
- Read more about it in the
- [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
- """
- ),
- ] = (
- webhooks or routing.APIRouter()
- )
- self.root_path = root_path or openapi_prefix
- self.state: Annotated[
- State,
- Doc(
- """
- A state object for the application. This is the same object for the
- entire application, it doesn't change from request to request.
-
- You normally woudln't use this in FastAPI, for most of the cases you
- would instead use FastAPI dependencies.
-
- This is simply inherited from Starlette.
-
- Read more about it in the
- [Starlette docs for Applications](https://www.starlette.io/applications/#storing-state-on-the-app-instance).
- """
- ),
- ] = State()
- self.dependency_overrides: Annotated[
- Dict[Callable[..., Any], Callable[..., Any]],
- Doc(
- """
- A dictionary with overrides for the dependencies.
-
- Each key is the original dependency callable, and the value is the
- actual dependency that should be called.
-
- This is for testing, to replace expensive dependencies with testing
- versions.
-
- Read more about it in the
- [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).
- """
- ),
- ] = {}
- self.router: routing.APIRouter = routing.APIRouter(
- routes=routes,
- redirect_slashes=redirect_slashes,
- dependency_overrides_provider=self,
- on_startup=on_startup,
- on_shutdown=on_shutdown,
- lifespan=lifespan,
- default_response_class=default_response_class,
- dependencies=dependencies,
- callbacks=callbacks,
- deprecated=deprecated,
- include_in_schema=include_in_schema,
- responses=responses,
- generate_unique_id_function=generate_unique_id_function,
- )
- self.exception_handlers: Dict[
- Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
- ] = ({} if exception_handlers is None else dict(exception_handlers))
- self.exception_handlers.setdefault(HTTPException, http_exception_handler)
- self.exception_handlers.setdefault(
- RequestValidationError, request_validation_exception_handler
- )
- self.exception_handlers.setdefault(
- WebSocketRequestValidationError,
- # Starlette still has incorrect type specification for the handlers
- websocket_request_validation_exception_handler, # type: ignore
- )
-
- self.user_middleware: List[Middleware] = (
- [] if middleware is None else list(middleware)
- )
- self.middleware_stack: Union[ASGIApp, None] = None
- self.setup()
-
- def build_middleware_stack(self) -> ASGIApp:
- # Duplicate/override from Starlette to add AsyncExitStackMiddleware
- # inside of ExceptionMiddleware, inside of custom user middlewares
- debug = self.debug
- error_handler = None
- exception_handlers = {}
-
- for key, value in self.exception_handlers.items():
- if key in (500, Exception):
- error_handler = value
- else:
- exception_handlers[key] = value
-
- middleware = (
- [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
- + self.user_middleware
- + [
- Middleware(
- ExceptionMiddleware, handlers=exception_handlers, debug=debug
- ),
- # Add FastAPI-specific AsyncExitStackMiddleware for dependencies with
- # contextvars.
- # This needs to happen after user middlewares because those create a
- # new contextvars context copy by using a new AnyIO task group.
- # The initial part of dependencies with 'yield' is executed in the
- # FastAPI code, inside all the middlewares. However, the teardown part
- # (after 'yield') is executed in the AsyncExitStack in this middleware.
- # If the AsyncExitStack lived outside of the custom middlewares and
- # contextvars were set in a dependency with 'yield' in that internal
- # contextvars context, the values would not be available in the
- # outer context of the AsyncExitStack.
- # By placing the middleware and the AsyncExitStack here, inside all
- # user middlewares, the code before and after 'yield' in dependencies
- # with 'yield' is executed in the same contextvars context. Thus, all values
- # set in contextvars before 'yield' are still available after 'yield,' as
- # expected.
- # Additionally, by having this AsyncExitStack here, after the
- # ExceptionMiddleware, dependencies can now catch handled exceptions,
- # e.g. HTTPException, to customize the teardown code (e.g. DB session
- # rollback).
- Middleware(AsyncExitStackMiddleware),
- ]
- )
-
- app = self.router
- for cls, options in reversed(middleware):
- app = cls(app=app, **options)
- return app
-
- def openapi(self) -> Dict[str, Any]:
- """
- Generate the OpenAPI schema of the application. This is called by FastAPI
- internally.
-
- The first time it is called it stores the result in the attribute
- `app.openapi_schema`, and next times it is called, it just returns that same
- result. To avoid the cost of generating the schema every time.
-
- If you need to modify the generated OpenAPI schema, you could modify it.
-
- Read more in the
- [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
- """
- if not self.openapi_schema:
- self.openapi_schema = get_openapi(
- title=self.title,
- version=self.version,
- openapi_version=self.openapi_version,
- summary=self.summary,
- description=self.description,
- terms_of_service=self.terms_of_service,
- contact=self.contact,
- license_info=self.license_info,
- routes=self.routes,
- webhooks=self.webhooks.routes,
- tags=self.openapi_tags,
- servers=self.servers,
- separate_input_output_schemas=self.separate_input_output_schemas,
- )
- return self.openapi_schema
-
- def setup(self) -> None:
- if self.openapi_url:
- urls = (server_data.get("url") for server_data in self.servers)
- server_urls = {url for url in urls if url}
-
- async def openapi(req: Request) -> JSONResponse:
- root_path = req.scope.get("root_path", "").rstrip("/")
- if root_path not in server_urls:
- if root_path and self.root_path_in_servers:
- self.servers.insert(0, {"url": root_path})
- server_urls.add(root_path)
- return JSONResponse(self.openapi())
-
- self.add_route(self.openapi_url, openapi, include_in_schema=False)
- if self.openapi_url and self.docs_url:
-
- async def swagger_ui_html(req: Request) -> HTMLResponse:
- root_path = req.scope.get("root_path", "").rstrip("/")
- openapi_url = root_path + self.openapi_url
- oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
- if oauth2_redirect_url:
- oauth2_redirect_url = root_path + oauth2_redirect_url
- return get_swagger_ui_html(
- openapi_url=openapi_url,
- title=self.title + " - Swagger UI",
- oauth2_redirect_url=oauth2_redirect_url,
- init_oauth=self.swagger_ui_init_oauth,
- swagger_ui_parameters=self.swagger_ui_parameters,
- )
-
- self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)
-
- if self.swagger_ui_oauth2_redirect_url:
-
- async def swagger_ui_redirect(req: Request) -> HTMLResponse:
- return get_swagger_ui_oauth2_redirect_html()
-
- self.add_route(
- self.swagger_ui_oauth2_redirect_url,
- swagger_ui_redirect,
- include_in_schema=False,
- )
- if self.openapi_url and self.redoc_url:
-
- async def redoc_html(req: Request) -> HTMLResponse:
- root_path = req.scope.get("root_path", "").rstrip("/")
- openapi_url = root_path + self.openapi_url
- return get_redoc_html(
- openapi_url=openapi_url, title=self.title + " - ReDoc"
- )
-
- self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
-
- async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
- if self.root_path:
- scope["root_path"] = self.root_path
- await super().__call__(scope, receive, send)
-
- def add_api_route(
- self,
- path: str,
- endpoint: Callable[..., Coroutine[Any, Any, Response]],
- *,
- response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
- response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[List[str]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
- response_model_by_alias: bool = True,
- response_model_exclude_unset: bool = False,
- response_model_exclude_defaults: bool = False,
- response_model_exclude_none: bool = False,
- include_in_schema: bool = True,
- response_class: Union[Type[Response], DefaultPlaceholder] = Default(
- JSONResponse
- ),
- name: Optional[str] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
- generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
- generate_unique_id
- ),
- ) -> None:
- self.router.add_api_route(
- path,
- endpoint=endpoint,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- methods=methods,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def api_route(
- self,
- path: str,
- *,
- response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[List[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
- response_description: str = "Successful Response",
- responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[List[str]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
- response_model_by_alias: bool = True,
- response_model_exclude_unset: bool = False,
- response_model_exclude_defaults: bool = False,
- response_model_exclude_none: bool = False,
- include_in_schema: bool = True,
- response_class: Type[Response] = Default(JSONResponse),
- name: Optional[str] = None,
- openapi_extra: Optional[Dict[str, Any]] = None,
- generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
- generate_unique_id
- ),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- def decorator(func: DecoratedCallable) -> DecoratedCallable:
- self.router.add_api_route(
- path,
- func,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- methods=methods,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
- return func
-
- return decorator
-
- def add_api_websocket_route(
- self,
- path: str,
- endpoint: Callable[..., Any],
- name: Optional[str] = None,
- *,
- dependencies: Optional[Sequence[Depends]] = None,
- ) -> None:
- self.router.add_api_websocket_route(
- path,
- endpoint,
- name=name,
- dependencies=dependencies,
- )
-
- def websocket(
- self,
- path: Annotated[
- str,
- Doc(
- """
- WebSocket path.
- """
- ),
- ],
- name: Annotated[
- Optional[str],
- Doc(
- """
- A name for the WebSocket. Only used internally.
- """
- ),
- ] = None,
- *,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be used for this
- WebSocket.
-
- Read more about it in the
- [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
- """
- ),
- ] = None,
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Decorate a WebSocket function.
-
- Read more about it in the
- [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
-
- **Example**
-
- ```python
- from fastapi import FastAPI, WebSocket
-
- app = FastAPI()
-
- @app.websocket("/ws")
- async def websocket_endpoint(websocket: WebSocket):
- await websocket.accept()
- while True:
- data = await websocket.receive_text()
- await websocket.send_text(f"Message text was: {data}")
- ```
- """
-
- def decorator(func: DecoratedCallable) -> DecoratedCallable:
- self.add_api_websocket_route(
- path,
- func,
- name=name,
- dependencies=dependencies,
- )
- return func
-
- return decorator
-
- def include_router(
- self,
- router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],
- *,
- prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to all the *path operations* in this
- router.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to all the
- *path operations* in this router.
-
- Read more about it in the
- [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
-
- **Example**
-
- ```python
- from fastapi import Depends, FastAPI
-
- from .dependencies import get_token_header
- from .internal import admin
-
- app = FastAPI()
-
- app.include_router(
- admin.router,
- dependencies=[Depends(get_token_header)],
- )
- ```
- """
- ),
- ] = None,
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses to be shown in OpenAPI.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
-
- And in the
- [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark all the *path operations* in this router as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- from .internal import old_api
-
- app = FastAPI()
-
- app.include_router(
- old_api.router,
- deprecated=True,
- )
- ```
- """
- ),
- ] = None,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include (or not) all the *path operations* in this router in the
- generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
-
- from .internal import old_api
-
- app = FastAPI()
-
- app.include_router(
- old_api.router,
- include_in_schema=False,
- )
- ```
- """
- ),
- ] = True,
- default_response_class: Annotated[
- Type[Response],
- Doc(
- """
- Default response class to be used for the *path operations* in this
- router.
-
- Read more in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
-
- **Example**
-
- ```python
- from fastapi import FastAPI
- from fastapi.responses import ORJSONResponse
-
- from .internal import old_api
-
- app = FastAPI()
-
- app.include_router(
- old_api.router,
- default_response_class=ORJSONResponse,
- )
- ```
- """
- ),
- ] = Default(JSONResponse),
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> None:
- """
- Include an `APIRouter` in the same app.
-
- Read more about it in the
- [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- from .users import users_router
-
- app = FastAPI()
-
- app.include_router(users_router)
- ```
- """
- self.router.include_router(
- router,
- prefix=prefix,
- tags=tags,
- dependencies=dependencies,
- responses=responses,
- deprecated=deprecated,
- include_in_schema=include_in_schema,
- default_response_class=default_response_class,
- callbacks=callbacks,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def get(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP GET operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.get("/items/")
- def read_items():
- return [{"name": "Empanada"}, {"name": "Arepa"}]
- ```
- """
- return self.router.get(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def put(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP PUT operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
- from pydantic import BaseModel
-
- class Item(BaseModel):
- name: str
- description: str | None = None
-
- app = FastAPI()
-
- @app.put("/items/{item_id}")
- def replace_item(item_id: str, item: Item):
- return {"message": "Item replaced", "id": item_id}
- ```
- """
- return self.router.put(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def post(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP POST operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
- from pydantic import BaseModel
-
- class Item(BaseModel):
- name: str
- description: str | None = None
-
- app = FastAPI()
-
- @app.post("/items/")
- def create_item(item: Item):
- return {"message": "Item created"}
- ```
- """
- return self.router.post(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def delete(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP DELETE operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.delete("/items/{item_id}")
- def delete_item(item_id: str):
- return {"message": "Item deleted"}
- ```
- """
- return self.router.delete(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def options(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP OPTIONS operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.options("/items/")
- def get_item_options():
- return {"additions": ["Aji", "Guacamole"]}
- ```
- """
- return self.router.options(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def head(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP HEAD operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI, Response
-
- app = FastAPI()
-
- @app.head("/items/", status_code=204)
- def get_items_headers(response: Response):
- response.headers["X-Cat-Dog"] = "Alone in the world"
- ```
- """
- return self.router.head(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def patch(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP PATCH operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
- from pydantic import BaseModel
-
- class Item(BaseModel):
- name: str
- description: str | None = None
-
- app = FastAPI()
-
- @app.patch("/items/")
- def update_item(item: Item):
- return {"message": "Item updated in place"}
- ```
- """
- return self.router.patch(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def trace(
- self,
- path: Annotated[
- str,
- Doc(
- """
- The URL path to be used for this *path operation*.
-
- For example, in `http://example.com/items`, the path is `/items`.
- """
- ),
- ],
- *,
- response_model: Annotated[
- Any,
- Doc(
- """
- The type to use for the response.
-
- It could be any valid Pydantic *field* type. So, it doesn't have to
- be a Pydantic model, it could be other things, like a `list`, `dict`,
- etc.
-
- It will be used for:
-
- * Documentation: the generated OpenAPI (and the UI at `/docs`) will
- show it as the response (JSON Schema).
- * Serialization: you could return an arbitrary object and the
- `response_model` would be used to serialize that object into the
- corresponding JSON.
- * Filtering: the JSON sent to the client will only contain the data
- (fields) defined in the `response_model`. If you returned an object
- that contains an attribute `password` but the `response_model` does
- not include that field, the JSON sent to the client would not have
- that `password`.
- * Validation: whatever you return will be serialized with the
- `response_model`, converting any data as necessary to generate the
- corresponding JSON. But if the data in the object returned is not
- valid, that would mean a violation of the contract with the client,
- so it's an error from the API developer. So, FastAPI will raise an
- error and return a 500 error code (Internal Server Error).
-
- Read more about it in the
- [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
- """
- ),
- ] = Default(None),
- status_code: Annotated[
- Optional[int],
- Doc(
- """
- The default status code to be used for the response.
-
- You could override the status code by returning a response directly.
-
- Read more about it in the
- [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
- """
- ),
- ] = None,
- tags: Annotated[
- Optional[List[Union[str, Enum]]],
- Doc(
- """
- A list of tags to be applied to the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
- """
- ),
- ] = None,
- dependencies: Annotated[
- Optional[Sequence[Depends]],
- Doc(
- """
- A list of dependencies (using `Depends()`) to be applied to the
- *path operation*.
-
- Read more about it in the
- [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
- """
- ),
- ] = None,
- summary: Annotated[
- Optional[str],
- Doc(
- """
- A summary for the *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- description: Annotated[
- Optional[str],
- Doc(
- """
- A description for the *path operation*.
-
- If not provided, it will be extracted automatically from the docstring
- of the *path operation function*.
-
- It can contain Markdown.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
- """
- ),
- ] = None,
- response_description: Annotated[
- str,
- Doc(
- """
- The description for the default response.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = "Successful Response",
- responses: Annotated[
- Optional[Dict[Union[int, str], Dict[str, Any]]],
- Doc(
- """
- Additional responses that could be returned by this *path operation*.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- deprecated: Annotated[
- Optional[bool],
- Doc(
- """
- Mark this *path operation* as deprecated.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
- """
- ),
- ] = None,
- operation_id: Annotated[
- Optional[str],
- Doc(
- """
- Custom operation ID to be used by this *path operation*.
-
- By default, it is generated automatically.
-
- If you provide a custom operation ID, you need to make sure it is
- unique for the whole API.
-
- You can customize the
- operation ID generation with the parameter
- `generate_unique_id_function` in the `FastAPI` class.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = None,
- response_model_include: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to include only certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_exclude: Annotated[
- Optional[IncEx],
- Doc(
- """
- Configuration passed to Pydantic to exclude certain fields in the
- response data.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = None,
- response_model_by_alias: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response model
- should be serialized by alias when an alias is used.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
- """
- ),
- ] = True,
- response_model_exclude_unset: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that were not set and
- have their default values. This is different from
- `response_model_exclude_defaults` in that if the fields are set,
- they will be included in the response, even if the value is the same
- as the default.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_defaults: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data
- should have all the fields, including the ones that have the same value
- as the default. This is different from `response_model_exclude_unset`
- in that if the fields are set but contain the same default values,
- they will be excluded from the response.
-
- When `True`, default values are omitted from the response.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
- """
- ),
- ] = False,
- response_model_exclude_none: Annotated[
- bool,
- Doc(
- """
- Configuration passed to Pydantic to define if the response data should
- exclude fields set to `None`.
-
- This is much simpler (less smart) than `response_model_exclude_unset`
- and `response_model_exclude_defaults`. You probably want to use one of
- those two instead of this one, as those allow returning `None` values
- when it makes sense.
-
- Read more about it in the
- [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
- """
- ),
- ] = False,
- include_in_schema: Annotated[
- bool,
- Doc(
- """
- Include this *path operation* in the generated OpenAPI schema.
-
- This affects the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
- """
- ),
- ] = True,
- response_class: Annotated[
- Type[Response],
- Doc(
- """
- Response class to be used for this *path operation*.
-
- This will not be used if you return a response directly.
-
- Read more about it in the
- [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
- """
- ),
- ] = Default(JSONResponse),
- name: Annotated[
- Optional[str],
- Doc(
- """
- Name for this *path operation*. Only used internally.
- """
- ),
- ] = None,
- callbacks: Annotated[
- Optional[List[BaseRoute]],
- Doc(
- """
- List of *path operations* that will be used as OpenAPI callbacks.
-
- This is only for OpenAPI documentation, the callbacks won't be used
- directly.
-
- It will be added to the generated OpenAPI (e.g. visible at `/docs`).
-
- Read more about it in the
- [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
- """
- ),
- ] = None,
- openapi_extra: Annotated[
- Optional[Dict[str, Any]],
- Doc(
- """
- Extra metadata to be included in the OpenAPI schema for this *path
- operation*.
-
- Read more about it in the
- [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
- """
- ),
- ] = None,
- generate_unique_id_function: Annotated[
- Callable[[routing.APIRoute], str],
- Doc(
- """
- Customize the function used to generate unique IDs for the *path
- operations* shown in the generated OpenAPI.
-
- This is particularly useful when automatically generating clients or
- SDKs for your API.
-
- Read more about it in the
- [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
- """
- ),
- ] = Default(generate_unique_id),
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a *path operation* using an HTTP TRACE operation.
-
- ## Example
-
- ```python
- from fastapi import FastAPI
-
- app = FastAPI()
-
- @app.put("/items/{item_id}")
- def trace_item(item_id: str):
- return None
- ```
- """
- return self.router.trace(
- path,
- response_model=response_model,
- status_code=status_code,
- tags=tags,
- dependencies=dependencies,
- summary=summary,
- description=description,
- response_description=response_description,
- responses=responses,
- deprecated=deprecated,
- operation_id=operation_id,
- response_model_include=response_model_include,
- response_model_exclude=response_model_exclude,
- response_model_by_alias=response_model_by_alias,
- response_model_exclude_unset=response_model_exclude_unset,
- response_model_exclude_defaults=response_model_exclude_defaults,
- response_model_exclude_none=response_model_exclude_none,
- include_in_schema=include_in_schema,
- response_class=response_class,
- name=name,
- callbacks=callbacks,
- openapi_extra=openapi_extra,
- generate_unique_id_function=generate_unique_id_function,
- )
-
- def websocket_route(
- self, path: str, name: Union[str, None] = None
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- def decorator(func: DecoratedCallable) -> DecoratedCallable:
- self.router.add_websocket_route(path, func, name=name)
- return func
-
- return decorator
-
- @deprecated(
- """
- on_event is deprecated, use lifespan event handlers instead.
-
- Read more about it in the
- [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
- """
- )
- def on_event(
- self,
- event_type: Annotated[
- str,
- Doc(
- """
- The type of event. `startup` or `shutdown`.
- """
- ),
- ],
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add an event handler for the application.
-
- `on_event` is deprecated, use `lifespan` event handlers instead.
-
- Read more about it in the
- [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
- """
- return self.router.on_event(event_type)
-
- def middleware(
- self,
- middleware_type: Annotated[
- str,
- Doc(
- """
- The type of middleware. Currently only supports `http`.
- """
- ),
- ],
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add a middleware to the application.
-
- Read more about it in the
- [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
-
- ## Example
-
- ```python
- import time
-
- from fastapi import FastAPI, Request
-
- app = FastAPI()
-
-
- @app.middleware("http")
- async def add_process_time_header(request: Request, call_next):
- start_time = time.time()
- response = await call_next(request)
- process_time = time.time() - start_time
- response.headers["X-Process-Time"] = str(process_time)
- return response
- ```
- """
-
- def decorator(func: DecoratedCallable) -> DecoratedCallable:
- self.add_middleware(BaseHTTPMiddleware, dispatch=func)
- return func
-
- return decorator
-
- def exception_handler(
- self,
- exc_class_or_status_code: Annotated[
- Union[int, Type[Exception]],
- Doc(
- """
- The Exception class this would handle, or a status code.
- """
- ),
- ],
- ) -> Callable[[DecoratedCallable], DecoratedCallable]:
- """
- Add an exception handler to the app.
-
- Read more about it in the
- [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
-
- ## Example
-
- ```python
- from fastapi import FastAPI, Request
- from fastapi.responses import JSONResponse
-
-
- class UnicornException(Exception):
- def __init__(self, name: str):
- self.name = name
-
-
- app = FastAPI()
-
-
- @app.exception_handler(UnicornException)
- async def unicorn_exception_handler(request: Request, exc: UnicornException):
- return JSONResponse(
- status_code=418,
- content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
- )
- ```
- """
-
- def decorator(func: DecoratedCallable) -> DecoratedCallable:
- self.add_exception_handler(exc_class_or_status_code, func)
- return func
-
- return decorator
diff --git a/server/venv/Lib/site-packages/fastapi/background.py b/server/venv/Lib/site-packages/fastapi/background.py
deleted file mode 100644
index 35ab1b2..0000000
--- a/server/venv/Lib/site-packages/fastapi/background.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from typing import Any, Callable
-
-from starlette.background import BackgroundTasks as StarletteBackgroundTasks
-from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined]
-
-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)
diff --git a/server/venv/Lib/site-packages/fastapi/concurrency.py b/server/venv/Lib/site-packages/fastapi/concurrency.py
deleted file mode 100644
index 754061c..0000000
--- a/server/venv/Lib/site-packages/fastapi/concurrency.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from contextlib import AsyncExitStack as AsyncExitStack # noqa
-from contextlib import asynccontextmanager as asynccontextmanager
-from typing import AsyncGenerator, ContextManager, TypeVar
-
-import anyio
-from anyio import CapacityLimiter
-from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa
-from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa
-from starlette.concurrency import ( # noqa
- run_until_first_complete as run_until_first_complete,
-)
-
-_T = TypeVar("_T")
-
-
-@asynccontextmanager
-async 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, None, limiter=exit_limiter
- )
- )
- if not ok:
- raise e
- else:
- await anyio.to_thread.run_sync(
- cm.__exit__, None, None, None, limiter=exit_limiter
- )
diff --git a/server/venv/Lib/site-packages/fastapi/datastructures.py b/server/venv/Lib/site-packages/fastapi/datastructures.py
deleted file mode 100644
index ce03e3c..0000000
--- a/server/venv/Lib/site-packages/fastapi/datastructures.py
+++ /dev/null
@@ -1,204 +0,0 @@
-from 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: F401
-from starlette.datastructures import Address as Address # noqa: F401
-from starlette.datastructures import FormData as FormData # noqa: F401
-from starlette.datastructures import Headers as Headers # noqa: F401
-from starlette.datastructures import QueryParams as QueryParams # noqa: F401
-from starlette.datastructures import State as State # noqa: F401
-from starlette.datastructures import UploadFile as StarletteUploadFile
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
-
-
-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: ignore
diff --git a/server/venv/Lib/site-packages/fastapi/dependencies/__init__.py b/server/venv/Lib/site-packages/fastapi/dependencies/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/server/venv/Lib/site-packages/fastapi/dependencies/models.py b/server/venv/Lib/site-packages/fastapi/dependencies/models.py
deleted file mode 100644
index 61ef006..0000000
--- a/server/venv/Lib/site-packages/fastapi/dependencies/models.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from typing import Any, Callable, List, Optional, Sequence
-
-from fastapi._compat import ModelField
-from fastapi.security.base import SecurityBase
-
-
-class SecurityRequirement:
- def __init__(
- self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None
- ):
- self.security_scheme = security_scheme
- self.scopes = scopes
-
-
-class Dependant:
- def __init__(
- self,
- *,
- path_params: Optional[List[ModelField]] = None,
- query_params: Optional[List[ModelField]] = None,
- header_params: Optional[List[ModelField]] = None,
- cookie_params: Optional[List[ModelField]] = None,
- body_params: Optional[List[ModelField]] = None,
- dependencies: Optional[List["Dependant"]] = None,
- security_schemes: Optional[List[SecurityRequirement]] = None,
- name: Optional[str] = None,
- call: Optional[Callable[..., Any]] = None,
- request_param_name: Optional[str] = None,
- websocket_param_name: Optional[str] = None,
- http_connection_param_name: Optional[str] = None,
- response_param_name: Optional[str] = None,
- background_tasks_param_name: Optional[str] = None,
- security_scopes_param_name: Optional[str] = None,
- security_scopes: Optional[List[str]] = None,
- use_cache: bool = True,
- path: Optional[str] = None,
- ) -> None:
- self.path_params = path_params or []
- self.query_params = query_params or []
- self.header_params = header_params or []
- self.cookie_params = cookie_params or []
- self.body_params = body_params or []
- self.dependencies = dependencies or []
- self.security_requirements = security_schemes or []
- self.request_param_name = request_param_name
- self.websocket_param_name = websocket_param_name
- self.http_connection_param_name = http_connection_param_name
- self.response_param_name = response_param_name
- self.background_tasks_param_name = background_tasks_param_name
- self.security_scopes = security_scopes
- self.security_scopes_param_name = security_scopes_param_name
- self.name = name
- self.call = call
- self.use_cache = use_cache
- # Store the path to be able to re-generate a dependable from it in overrides
- self.path = path
- # Save the cache key at creation to optimize performance
- self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or []))))
diff --git a/server/venv/Lib/site-packages/fastapi/dependencies/utils.py b/server/venv/Lib/site-packages/fastapi/dependencies/utils.py
deleted file mode 100644
index 96e07a4..0000000
--- a/server/venv/Lib/site-packages/fastapi/dependencies/utils.py
+++ /dev/null
@@ -1,810 +0,0 @@
-import inspect
-from contextlib import contextmanager
-from copy import deepcopy
-from typing import (
- Any,
- Callable,
- Coroutine,
- Dict,
- ForwardRef,
- List,
- Mapping,
- Optional,
- Sequence,
- Tuple,
- Type,
- Union,
- cast,
-)
-
-import anyio
-from fastapi import params
-from fastapi._compat import (
- PYDANTIC_V2,
- ErrorWrapper,
- ModelField,
- Required,
- Undefined,
- _regenerate_error_with_loc,
- copy_field_info,
- create_body_model,
- evaluate_forwardref,
- field_annotation_is_scalar,
- get_annotation_from_field_info,
- get_missing_field_error,
- is_bytes_field,
- is_bytes_sequence_field,
- is_scalar_field,
- is_scalar_sequence_field,
- is_sequence_field,
- is_uploadfile_or_nonable_uploadfile_annotation,
- is_uploadfile_sequence_annotation,
- lenient_issubclass,
- sequence_types,
- serialize_sequence_value,
- value_is_sequence,
-)
-from fastapi.background import BackgroundTasks
-from fastapi.concurrency import (
- AsyncExitStack,
- asynccontextmanager,
- contextmanager_in_threadpool,
-)
-from fastapi.dependencies.models import Dependant, SecurityRequirement
-from fastapi.logger import logger
-from fastapi.security.base import SecurityBase
-from fastapi.security.oauth2 import OAuth2, SecurityScopes
-from fastapi.security.open_id_connect_url import OpenIdConnect
-from fastapi.utils import create_response_field, get_path_param_names
-from pydantic.fields import FieldInfo
-from starlette.background import BackgroundTasks as StarletteBackgroundTasks
-from starlette.concurrency import run_in_threadpool
-from starlette.datastructures import FormData, Headers, QueryParams, UploadFile
-from starlette.requests import HTTPConnection, Request
-from starlette.responses import Response
-from starlette.websockets import WebSocket
-from typing_extensions import Annotated, get_args, get_origin
-
-multipart_not_installed_error = (
- 'Form data requires "python-multipart" to be installed. \n'
- 'You can install "python-multipart" with: \n\n'
- "pip install python-multipart\n"
-)
-multipart_incorrect_install_error = (
- 'Form data requires "python-multipart" to be installed. '
- 'It seems you installed "multipart" instead. \n'
- 'You can remove "multipart" with: \n\n'
- "pip uninstall multipart\n\n"
- 'And then install "python-multipart" with: \n\n'
- "pip install python-multipart\n"
-)
-
-
-def check_file_field(field: ModelField) -> None:
- field_info = field.field_info
- if isinstance(field_info, params.Form):
- try:
- # __version__ is available in both multiparts, and can be mocked
- from multipart import __version__ # type: ignore
-
- assert __version__
- try:
- # parse_options_header is only available in the right multipart
- from multipart.multipart import parse_options_header # type: ignore
-
- assert parse_options_header
- except ImportError:
- logger.error(multipart_incorrect_install_error)
- raise RuntimeError(multipart_incorrect_install_error) from None
- except ImportError:
- logger.error(multipart_not_installed_error)
- raise RuntimeError(multipart_not_installed_error) from None
-
-
-def get_param_sub_dependant(
- *,
- param_name: str,
- depends: params.Depends,
- path: str,
- security_scopes: Optional[List[str]] = None,
-) -> Dependant:
- assert depends.dependency
- return get_sub_dependant(
- depends=depends,
- dependency=depends.dependency,
- path=path,
- name=param_name,
- security_scopes=security_scopes,
- )
-
-
-def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant:
- assert callable(
- depends.dependency
- ), "A parameter-less dependency must have a callable dependency"
- return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path)
-
-
-def get_sub_dependant(
- *,
- depends: params.Depends,
- dependency: Callable[..., Any],
- path: str,
- name: Optional[str] = None,
- security_scopes: Optional[List[str]] = None,
-) -> Dependant:
- security_requirement = None
- security_scopes = security_scopes or []
- if isinstance(depends, params.Security):
- dependency_scopes = depends.scopes
- security_scopes.extend(dependency_scopes)
- if isinstance(dependency, SecurityBase):
- use_scopes: List[str] = []
- if isinstance(dependency, (OAuth2, OpenIdConnect)):
- use_scopes = security_scopes
- security_requirement = SecurityRequirement(
- security_scheme=dependency, scopes=use_scopes
- )
- sub_dependant = get_dependant(
- path=path,
- call=dependency,
- name=name,
- security_scopes=security_scopes,
- use_cache=depends.use_cache,
- )
- if security_requirement:
- sub_dependant.security_requirements.append(security_requirement)
- return sub_dependant
-
-
-CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]]
-
-
-def get_flat_dependant(
- dependant: Dependant,
- *,
- skip_repeats: bool = False,
- visited: Optional[List[CacheKey]] = None,
-) -> Dependant:
- if visited is None:
- visited = []
- visited.append(dependant.cache_key)
-
- flat_dependant = Dependant(
- path_params=dependant.path_params.copy(),
- query_params=dependant.query_params.copy(),
- header_params=dependant.header_params.copy(),
- cookie_params=dependant.cookie_params.copy(),
- body_params=dependant.body_params.copy(),
- security_schemes=dependant.security_requirements.copy(),
- use_cache=dependant.use_cache,
- path=dependant.path,
- )
- for sub_dependant in dependant.dependencies:
- if skip_repeats and sub_dependant.cache_key in visited:
- continue
- flat_sub = get_flat_dependant(
- sub_dependant, skip_repeats=skip_repeats, visited=visited
- )
- flat_dependant.path_params.extend(flat_sub.path_params)
- flat_dependant.query_params.extend(flat_sub.query_params)
- flat_dependant.header_params.extend(flat_sub.header_params)
- flat_dependant.cookie_params.extend(flat_sub.cookie_params)
- flat_dependant.body_params.extend(flat_sub.body_params)
- flat_dependant.security_requirements.extend(flat_sub.security_requirements)
- return flat_dependant
-
-
-def get_flat_params(dependant: Dependant) -> List[ModelField]:
- flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
- return (
- flat_dependant.path_params
- + flat_dependant.query_params
- + flat_dependant.header_params
- + flat_dependant.cookie_params
- )
-
-
-def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
- signature = inspect.signature(call)
- globalns = getattr(call, "__globals__", {})
- typed_params = [
- inspect.Parameter(
- name=param.name,
- kind=param.kind,
- default=param.default,
- annotation=get_typed_annotation(param.annotation, globalns),
- )
- for param in signature.parameters.values()
- ]
- typed_signature = inspect.Signature(typed_params)
- return typed_signature
-
-
-def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any:
- if isinstance(annotation, str):
- annotation = ForwardRef(annotation)
- annotation = evaluate_forwardref(annotation, globalns, globalns)
- return annotation
-
-
-def get_typed_return_annotation(call: Callable[..., Any]) -> Any:
- signature = inspect.signature(call)
- annotation = signature.return_annotation
-
- if annotation is inspect.Signature.empty:
- return None
-
- globalns = getattr(call, "__globals__", {})
- return get_typed_annotation(annotation, globalns)
-
-
-def get_dependant(
- *,
- path: str,
- call: Callable[..., Any],
- name: Optional[str] = None,
- security_scopes: Optional[List[str]] = None,
- use_cache: bool = True,
-) -> Dependant:
- path_param_names = get_path_param_names(path)
- endpoint_signature = get_typed_signature(call)
- signature_params = endpoint_signature.parameters
- dependant = Dependant(
- call=call,
- name=name,
- path=path,
- security_scopes=security_scopes,
- use_cache=use_cache,
- )
- for param_name, param in signature_params.items():
- is_path_param = param_name in path_param_names
- type_annotation, depends, param_field = analyze_param(
- param_name=param_name,
- annotation=param.annotation,
- value=param.default,
- is_path_param=is_path_param,
- )
- if depends is not None:
- sub_dependant = get_param_sub_dependant(
- param_name=param_name,
- depends=depends,
- path=path,
- security_scopes=security_scopes,
- )
- dependant.dependencies.append(sub_dependant)
- continue
- if add_non_field_param_to_dependency(
- param_name=param_name,
- type_annotation=type_annotation,
- dependant=dependant,
- ):
- assert (
- param_field is None
- ), f"Cannot specify multiple FastAPI annotations for {param_name!r}"
- continue
- assert param_field is not None
- if is_body_param(param_field=param_field, is_path_param=is_path_param):
- dependant.body_params.append(param_field)
- else:
- add_param_to_fields(field=param_field, dependant=dependant)
- return dependant
-
-
-def add_non_field_param_to_dependency(
- *, param_name: str, type_annotation: Any, dependant: Dependant
-) -> Optional[bool]:
- if lenient_issubclass(type_annotation, Request):
- dependant.request_param_name = param_name
- return True
- elif lenient_issubclass(type_annotation, WebSocket):
- dependant.websocket_param_name = param_name
- return True
- elif lenient_issubclass(type_annotation, HTTPConnection):
- dependant.http_connection_param_name = param_name
- return True
- elif lenient_issubclass(type_annotation, Response):
- dependant.response_param_name = param_name
- return True
- elif lenient_issubclass(type_annotation, StarletteBackgroundTasks):
- dependant.background_tasks_param_name = param_name
- return True
- elif lenient_issubclass(type_annotation, SecurityScopes):
- dependant.security_scopes_param_name = param_name
- return True
- return None
-
-
-def analyze_param(
- *,
- param_name: str,
- annotation: Any,
- value: Any,
- is_path_param: bool,
-) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]:
- field_info = None
- depends = None
- type_annotation: Any = Any
- if (
- annotation is not inspect.Signature.empty
- and get_origin(annotation) is Annotated
- ):
- annotated_args = get_args(annotation)
- type_annotation = annotated_args[0]
- fastapi_annotations = [
- arg
- for arg in annotated_args[1:]
- if isinstance(arg, (FieldInfo, params.Depends))
- ]
- assert (
- len(fastapi_annotations) <= 1
- ), f"Cannot specify multiple `Annotated` FastAPI arguments for {param_name!r}"
- fastapi_annotation = next(iter(fastapi_annotations), None)
- if isinstance(fastapi_annotation, FieldInfo):
- # Copy `field_info` because we mutate `field_info.default` below.
- field_info = copy_field_info(
- field_info=fastapi_annotation, annotation=annotation
- )
- assert field_info.default is Undefined or field_info.default is Required, (
- f"`{field_info.__class__.__name__}` default value cannot be set in"
- f" `Annotated` for {param_name!r}. Set the default value with `=` instead."
- )
- if value is not inspect.Signature.empty:
- assert not is_path_param, "Path parameters cannot have default values"
- field_info.default = value
- else:
- field_info.default = Required
- elif isinstance(fastapi_annotation, params.Depends):
- depends = fastapi_annotation
- elif annotation is not inspect.Signature.empty:
- type_annotation = annotation
-
- if isinstance(value, params.Depends):
- assert depends is None, (
- "Cannot specify `Depends` in `Annotated` and default value"
- f" together for {param_name!r}"
- )
- assert field_info is None, (
- "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a"
- f" default value together for {param_name!r}"
- )
- depends = value
- elif isinstance(value, FieldInfo):
- assert field_info is None, (
- "Cannot specify FastAPI annotations in `Annotated` and default value"
- f" together for {param_name!r}"
- )
- field_info = value
- if PYDANTIC_V2:
- field_info.annotation = type_annotation
-
- if depends is not None and depends.dependency is None:
- depends.dependency = type_annotation
-
- if lenient_issubclass(
- type_annotation,
- (
- Request,
- WebSocket,
- HTTPConnection,
- Response,
- StarletteBackgroundTasks,
- SecurityScopes,
- ),
- ):
- assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}"
- assert (
- field_info is None
- ), f"Cannot specify FastAPI annotation for type {type_annotation!r}"
- elif field_info is None and depends is None:
- default_value = value if value is not inspect.Signature.empty else Required
- if is_path_param:
- # We might check here that `default_value is Required`, but the fact is that the same
- # parameter might sometimes be a path parameter and sometimes not. See
- # `tests/test_infer_param_optionality.py` for an example.
- field_info = params.Path(annotation=type_annotation)
- elif is_uploadfile_or_nonable_uploadfile_annotation(
- type_annotation
- ) or is_uploadfile_sequence_annotation(type_annotation):
- field_info = params.File(annotation=type_annotation, default=default_value)
- elif not field_annotation_is_scalar(annotation=type_annotation):
- field_info = params.Body(annotation=type_annotation, default=default_value)
- else:
- field_info = params.Query(annotation=type_annotation, default=default_value)
-
- field = None
- if field_info is not None:
- if is_path_param:
- assert isinstance(field_info, params.Path), (
- f"Cannot use `{field_info.__class__.__name__}` for path param"
- f" {param_name!r}"
- )
- elif (
- isinstance(field_info, params.Param)
- and getattr(field_info, "in_", None) is None
- ):
- field_info.in_ = params.ParamTypes.query
- use_annotation = get_annotation_from_field_info(
- type_annotation,
- field_info,
- param_name,
- )
- if not field_info.alias and getattr(field_info, "convert_underscores", None):
- alias = param_name.replace("_", "-")
- else:
- alias = field_info.alias or param_name
- field_info.alias = alias
- field = create_response_field(
- name=param_name,
- type_=use_annotation,
- default=field_info.default,
- alias=alias,
- required=field_info.default in (Required, Undefined),
- field_info=field_info,
- )
-
- return type_annotation, depends, field
-
-
-def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool:
- if is_path_param:
- assert is_scalar_field(
- field=param_field
- ), "Path params must be of one of the supported types"
- return False
- elif is_scalar_field(field=param_field):
- return False
- elif isinstance(
- param_field.field_info, (params.Query, params.Header)
- ) and is_scalar_sequence_field(param_field):
- return False
- else:
- assert isinstance(
- param_field.field_info, params.Body
- ), f"Param: {param_field.name} can only be a request body, using Body()"
- return True
-
-
-def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
- field_info = cast(params.Param, field.field_info)
- if field_info.in_ == params.ParamTypes.path:
- dependant.path_params.append(field)
- elif field_info.in_ == params.ParamTypes.query:
- dependant.query_params.append(field)
- elif field_info.in_ == params.ParamTypes.header:
- dependant.header_params.append(field)
- else:
- assert (
- field_info.in_ == params.ParamTypes.cookie
- ), f"non-body parameters must be in path, query, header or cookie: {field.name}"
- dependant.cookie_params.append(field)
-
-
-def is_coroutine_callable(call: Callable[..., Any]) -> bool:
- if inspect.isroutine(call):
- return inspect.iscoroutinefunction(call)
- if inspect.isclass(call):
- return False
- dunder_call = getattr(call, "__call__", None) # noqa: B004
- return inspect.iscoroutinefunction(dunder_call)
-
-
-def is_async_gen_callable(call: Callable[..., Any]) -> bool:
- if inspect.isasyncgenfunction(call):
- return True
- dunder_call = getattr(call, "__call__", None) # noqa: B004
- return inspect.isasyncgenfunction(dunder_call)
-
-
-def is_gen_callable(call: Callable[..., Any]) -> bool:
- if inspect.isgeneratorfunction(call):
- return True
- dunder_call = getattr(call, "__call__", None) # noqa: B004
- return inspect.isgeneratorfunction(dunder_call)
-
-
-async def solve_generator(
- *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any]
-) -> Any:
- if is_gen_callable(call):
- cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values))
- elif is_async_gen_callable(call):
- cm = asynccontextmanager(call)(**sub_values)
- return await stack.enter_async_context(cm)
-
-
-async def solve_dependencies(
- *,
- request: Union[Request, WebSocket],
- dependant: Dependant,
- body: Optional[Union[Dict[str, Any], FormData]] = None,
- background_tasks: Optional[StarletteBackgroundTasks] = None,
- response: Optional[Response] = None,
- dependency_overrides_provider: Optional[Any] = None,
- dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None,
-) -> Tuple[
- Dict[str, Any],
- List[Any],
- Optional[StarletteBackgroundTasks],
- Response,
- Dict[Tuple[Callable[..., Any], Tuple[str]], Any],
-]:
- values: Dict[str, Any] = {}
- errors: List[Any] = []
- if response is None:
- response = Response()
- del response.headers["content-length"]
- response.status_code = None # type: ignore
- dependency_cache = dependency_cache or {}
- sub_dependant: Dependant
- for sub_dependant in dependant.dependencies:
- sub_dependant.call = cast(Callable[..., Any], sub_dependant.call)
- sub_dependant.cache_key = cast(
- Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key
- )
- call = sub_dependant.call
- use_sub_dependant = sub_dependant
- if (
- dependency_overrides_provider
- and dependency_overrides_provider.dependency_overrides
- ):
- original_call = sub_dependant.call
- call = getattr(
- dependency_overrides_provider, "dependency_overrides", {}
- ).get(original_call, original_call)
- use_path: str = sub_dependant.path # type: ignore
- use_sub_dependant = get_dependant(
- path=use_path,
- call=call,
- name=sub_dependant.name,
- security_scopes=sub_dependant.security_scopes,
- )
-
- solved_result = await solve_dependencies(
- request=request,
- dependant=use_sub_dependant,
- body=body,
- background_tasks=background_tasks,
- response=response,
- dependency_overrides_provider=dependency_overrides_provider,
- dependency_cache=dependency_cache,
- )
- (
- sub_values,
- sub_errors,
- background_tasks,
- _, # the subdependency returns the same response we have
- sub_dependency_cache,
- ) = solved_result
- dependency_cache.update(sub_dependency_cache)
- if sub_errors:
- errors.extend(sub_errors)
- continue
- if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:
- solved = dependency_cache[sub_dependant.cache_key]
- elif is_gen_callable(call) or is_async_gen_callable(call):
- stack = request.scope.get("fastapi_astack")
- assert isinstance(stack, AsyncExitStack)
- solved = await solve_generator(
- call=call, stack=stack, sub_values=sub_values
- )
- elif is_coroutine_callable(call):
- solved = await call(**sub_values)
- else:
- solved = await run_in_threadpool(call, **sub_values)
- if sub_dependant.name is not None:
- values[sub_dependant.name] = solved
- if sub_dependant.cache_key not in dependency_cache:
- dependency_cache[sub_dependant.cache_key] = solved
- path_values, path_errors = request_params_to_args(
- dependant.path_params, request.path_params
- )
- query_values, query_errors = request_params_to_args(
- dependant.query_params, request.query_params
- )
- header_values, header_errors = request_params_to_args(
- dependant.header_params, request.headers
- )
- cookie_values, cookie_errors = request_params_to_args(
- dependant.cookie_params, request.cookies
- )
- values.update(path_values)
- values.update(query_values)
- values.update(header_values)
- values.update(cookie_values)
- errors += path_errors + query_errors + header_errors + cookie_errors
- if dependant.body_params:
- (
- body_values,
- body_errors,
- ) = await request_body_to_args( # body_params checked above
- required_params=dependant.body_params, received_body=body
- )
- values.update(body_values)
- errors.extend(body_errors)
- if dependant.http_connection_param_name:
- values[dependant.http_connection_param_name] = request
- if dependant.request_param_name and isinstance(request, Request):
- values[dependant.request_param_name] = request
- elif dependant.websocket_param_name and isinstance(request, WebSocket):
- values[dependant.websocket_param_name] = request
- if dependant.background_tasks_param_name:
- if background_tasks is None:
- background_tasks = BackgroundTasks()
- values[dependant.background_tasks_param_name] = background_tasks
- if dependant.response_param_name:
- values[dependant.response_param_name] = response
- if dependant.security_scopes_param_name:
- values[dependant.security_scopes_param_name] = SecurityScopes(
- scopes=dependant.security_scopes
- )
- return values, errors, background_tasks, response, dependency_cache
-
-
-def request_params_to_args(
- required_params: Sequence[ModelField],
- received_params: Union[Mapping[str, Any], QueryParams, Headers],
-) -> Tuple[Dict[str, Any], List[Any]]:
- values = {}
- errors = []
- for field in required_params:
- if is_scalar_sequence_field(field) and isinstance(
- received_params, (QueryParams, Headers)
- ):
- value = received_params.getlist(field.alias) or field.default
- else:
- value = received_params.get(field.alias)
- field_info = field.field_info
- assert isinstance(
- field_info, params.Param
- ), "Params must be subclasses of Param"
- loc = (field_info.in_.value, field.alias)
- if value is None:
- if field.required:
- errors.append(get_missing_field_error(loc=loc))
- else:
- values[field.name] = deepcopy(field.default)
- continue
- v_, errors_ = field.validate(value, values, loc=loc)
- if isinstance(errors_, ErrorWrapper):
- errors.append(errors_)
- elif isinstance(errors_, list):
- new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=())
- errors.extend(new_errors)
- else:
- values[field.name] = v_
- return values, errors
-
-
-async def request_body_to_args(
- required_params: List[ModelField],
- received_body: Optional[Union[Dict[str, Any], FormData]],
-) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
- values = {}
- errors: List[Dict[str, Any]] = []
- if required_params:
- field = required_params[0]
- field_info = field.field_info
- embed = getattr(field_info, "embed", None)
- field_alias_omitted = len(required_params) == 1 and not embed
- if field_alias_omitted:
- received_body = {field.alias: received_body}
-
- for field in required_params:
- loc: Tuple[str, ...]
- if field_alias_omitted:
- loc = ("body",)
- else:
- loc = ("body", field.alias)
-
- value: Optional[Any] = None
- if received_body is not None:
- if (is_sequence_field(field)) and isinstance(received_body, FormData):
- value = received_body.getlist(field.alias)
- else:
- try:
- value = received_body.get(field.alias)
- except AttributeError:
- errors.append(get_missing_field_error(loc))
- continue
- if (
- value is None
- or (isinstance(field_info, params.Form) and value == "")
- or (
- isinstance(field_info, params.Form)
- and is_sequence_field(field)
- and len(value) == 0
- )
- ):
- if field.required:
- errors.append(get_missing_field_error(loc))
- else:
- values[field.name] = deepcopy(field.default)
- continue
- if (
- isinstance(field_info, params.File)
- and is_bytes_field(field)
- and isinstance(value, UploadFile)
- ):
- value = await value.read()
- elif (
- is_bytes_sequence_field(field)
- and isinstance(field_info, params.File)
- and value_is_sequence(value)
- ):
- # For types
- assert isinstance(value, sequence_types) # type: ignore[arg-type]
- results: List[Union[bytes, str]] = []
-
- async def process_fn(
- fn: Callable[[], Coroutine[Any, Any, Any]]
- ) -> None:
- result = await fn()
- results.append(result) # noqa: B023
-
- async with anyio.create_task_group() as tg:
- for sub_value in value:
- tg.start_soon(process_fn, sub_value.read)
- value = serialize_sequence_value(field=field, value=results)
-
- v_, errors_ = field.validate(value, values, loc=loc)
-
- if isinstance(errors_, list):
- errors.extend(errors_)
- elif errors_:
- errors.append(errors_)
- else:
- values[field.name] = v_
- return values, errors
-
-
-def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]:
- flat_dependant = get_flat_dependant(dependant)
- if not flat_dependant.body_params:
- return None
- first_param = flat_dependant.body_params[0]
- field_info = first_param.field_info
- embed = getattr(field_info, "embed", None)
- body_param_names_set = {param.name for param in flat_dependant.body_params}
- if len(body_param_names_set) == 1 and not embed:
- check_file_field(first_param)
- return first_param
- # If one field requires to embed, all have to be embedded
- # in case a sub-dependency is evaluated with a single unique body field
- # That is combined (embedded) with other body fields
- for param in flat_dependant.body_params:
- setattr(param.field_info, "embed", True) # noqa: B010
- model_name = "Body_" + name
- BodyModel = create_body_model(
- fields=flat_dependant.body_params, model_name=model_name
- )
- required = any(True for f in flat_dependant.body_params if f.required)
- BodyFieldInfo_kwargs: Dict[str, Any] = {
- "annotation": BodyModel,
- "alias": "body",
- }
- if not required:
- BodyFieldInfo_kwargs["default"] = None
- if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params):
- BodyFieldInfo: Type[params.Body] = params.File
- elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params):
- BodyFieldInfo = params.Form
- else:
- BodyFieldInfo = params.Body
-
- body_param_media_types = [
- f.field_info.media_type
- for f in flat_dependant.body_params
- if isinstance(f.field_info, params.Body)
- ]
- if len(set(body_param_media_types)) == 1:
- BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0]
- final_field = create_response_field(
- name="body",
- type_=BodyModel,
- required=required,
- alias="body",
- field_info=BodyFieldInfo(**BodyFieldInfo_kwargs),
- )
- check_file_field(final_field)
- return final_field
diff --git a/server/venv/Lib/site-packages/fastapi/encoders.py b/server/venv/Lib/site-packages/fastapi/encoders.py
deleted file mode 100644
index e501713..0000000
--- a/server/venv/Lib/site-packages/fastapi/encoders.py
+++ /dev/null
@@ -1,341 +0,0 @@
-import dataclasses
-import datetime
-from collections import defaultdict, deque
-from decimal import Decimal
-from enum import Enum
-from ipaddress import (
- IPv4Address,
- IPv4Interface,
- IPv4Network,
- IPv6Address,
- IPv6Interface,
- IPv6Network,
-)
-from pathlib import Path, PurePath
-from re import Pattern
-from types import GeneratorType
-from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
-from uuid import UUID
-
-from fastapi.types import IncEx
-from pydantic import BaseModel
-from pydantic.color import Color
-from pydantic.networks import AnyUrl, NameEmail
-from pydantic.types import SecretBytes, SecretStr
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
-
-from ._compat import PYDANTIC_V2, Url, _model_dump
-
-
-# Taken from Pydantic v1 as is
-def 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, 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,
- )
diff --git a/server/venv/Lib/site-packages/fastapi/exception_handlers.py b/server/venv/Lib/site-packages/fastapi/exception_handlers.py
deleted file mode 100644
index 6c2ba7f..0000000
--- a/server/venv/Lib/site-packages/fastapi/exception_handlers.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from fastapi.encoders import jsonable_encoder
-from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
-from fastapi.utils import is_body_allowed_for_status_code
-from fastapi.websockets import WebSocket
-from starlette.exceptions import HTTPException
-from starlette.requests import Request
-from starlette.responses import JSONResponse, Response
-from 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())
- )
diff --git a/server/venv/Lib/site-packages/fastapi/exceptions.py b/server/venv/Lib/site-packages/fastapi/exceptions.py
deleted file mode 100644
index 680d288..0000000
--- a/server/venv/Lib/site-packages/fastapi/exceptions.py
+++ /dev/null
@@ -1,176 +0,0 @@
-from typing import Any, Dict, Optional, Sequence, Type, Union
-
-from pydantic import BaseModel, create_model
-from starlette.exceptions import HTTPException as StarletteHTTPException
-from starlette.exceptions import WebSocketException as StarletteWebSocketException
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
-
-
-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 message
diff --git a/server/venv/Lib/site-packages/fastapi/logger.py b/server/venv/Lib/site-packages/fastapi/logger.py
deleted file mode 100644
index 5b2c4ad..0000000
--- a/server/venv/Lib/site-packages/fastapi/logger.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import logging
-
-logger = logging.getLogger("fastapi")
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/__init__.py b/server/venv/Lib/site-packages/fastapi/middleware/__init__.py
deleted file mode 100644
index 620296d..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from starlette.middleware import Middleware as Middleware
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py b/server/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py
deleted file mode 100644
index 30a0ae6..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/asyncexitstack.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from typing import Optional
-
-from fastapi.concurrency import AsyncExitStack
-from starlette.types import ASGIApp, Receive, Scope, Send
-
-
-class AsyncExitStackMiddleware:
- def __init__(self, app: ASGIApp, context_name: str = "fastapi_astack") -> None:
- self.app = app
- self.context_name = context_name
-
- async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
- dependency_exception: Optional[Exception] = None
- async with AsyncExitStack() as stack:
- scope[self.context_name] = stack
- try:
- await self.app(scope, receive, send)
- except Exception as e:
- dependency_exception = e
- raise e
- if dependency_exception:
- # This exception was possibly handled by the dependency but it should
- # still bubble up so that the ServerErrorMiddleware can return a 500
- # or the ExceptionMiddleware can catch and handle any other exceptions
- raise dependency_exception
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/cors.py b/server/venv/Lib/site-packages/fastapi/middleware/cors.py
deleted file mode 100644
index 8dfaad0..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/cors.py
+++ /dev/null
@@ -1 +0,0 @@
-from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/gzip.py b/server/venv/Lib/site-packages/fastapi/middleware/gzip.py
deleted file mode 100644
index bbeb2cc..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/gzip.py
+++ /dev/null
@@ -1 +0,0 @@
-from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py b/server/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py
deleted file mode 100644
index b7a3d8e..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/httpsredirect.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from starlette.middleware.httpsredirect import ( # noqa
- HTTPSRedirectMiddleware as HTTPSRedirectMiddleware,
-)
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/trustedhost.py b/server/venv/Lib/site-packages/fastapi/middleware/trustedhost.py
deleted file mode 100644
index 08d7e03..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/trustedhost.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from starlette.middleware.trustedhost import ( # noqa
- TrustedHostMiddleware as TrustedHostMiddleware,
-)
diff --git a/server/venv/Lib/site-packages/fastapi/middleware/wsgi.py b/server/venv/Lib/site-packages/fastapi/middleware/wsgi.py
deleted file mode 100644
index c4c6a79..0000000
--- a/server/venv/Lib/site-packages/fastapi/middleware/wsgi.py
+++ /dev/null
@@ -1 +0,0 @@
-from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa
diff --git a/server/venv/Lib/site-packages/fastapi/openapi/__init__.py b/server/venv/Lib/site-packages/fastapi/openapi/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/server/venv/Lib/site-packages/fastapi/openapi/constants.py b/server/venv/Lib/site-packages/fastapi/openapi/constants.py
deleted file mode 100644
index d724ee3..0000000
--- a/server/venv/Lib/site-packages/fastapi/openapi/constants.py
+++ /dev/null
@@ -1,3 +0,0 @@
-METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"}
-REF_PREFIX = "#/components/schemas/"
-REF_TEMPLATE = "#/components/schemas/{model}"
diff --git a/server/venv/Lib/site-packages/fastapi/openapi/docs.py b/server/venv/Lib/site-packages/fastapi/openapi/docs.py
deleted file mode 100644
index 8cf0d17..0000000
--- a/server/venv/Lib/site-packages/fastapi/openapi/docs.py
+++ /dev/null
@@ -1,344 +0,0 @@
-import json
-from typing import Any, Dict, Optional
-
-from fastapi.encoders import jsonable_encoder
-from starlette.responses import HTMLResponse
-from typing_extensions import Annotated, Doc # type: ignore [attr-defined]
-
-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 `HTTPX - A next-generation HTTP client for Python.
- - - -HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated -command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync -and async APIs**. - ---- - -Install HTTPX using pip: - -```shell -$ pip install httpx -``` - -Now, let's get started: - -```pycon ->>> import httpx ->>> r = httpx.get('https://www.example.org/') ->>> r -- -
- -Sending a request... - -- -
- -## Features - -HTTPX builds on the well-established usability of `requests`, and gives you: - -* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). -* An integrated command-line client. -* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). -* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). -* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/#calling-into-python-web-apps) or [ASGI applications](https://www.python-httpx.org/async/#calling-into-python-web-apps). -* Strict timeouts everywhere. -* Fully type annotated. -* 100% test coverage. - -Plus all the standard features of `requests`... - -* International Domains and URLs -* Keep-Alive & Connection Pooling -* Sessions with Cookie Persistence -* Browser-style SSL Verification -* Basic/Digest Authentication -* Elegant Key/Value Cookies -* Automatic Decompression -* Automatic Content Decoding -* Unicode Response Bodies -* Multipart File Uploads -* HTTP(S) Proxy Support -* Connection Timeouts -* Streaming Downloads -* .netrc Support -* Chunked Requests - -## Installation - -Install with pip: - -```shell -$ pip install httpx -``` - -Or, to include the optional HTTP/2 support, use: - -```shell -$ pip install httpx[http2] -``` - -HTTPX requires Python 3.8+. - -## Documentation - -Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). - -For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). - -For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. - -The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. - -To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). - -## Contribute - -If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. - -## Dependencies - -The HTTPX project relies on these excellent libraries: - -* `httpcore` - The underlying transport implementation for `httpx`. - * `h11` - HTTP/1.1 support. -* `certifi` - SSL certificates. -* `idna` - Internationalized domain name support. -* `sniffio` - Async library autodetection. - -As well as these optional installs: - -* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* -* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* -* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* -* `click` - Command line client support. *(Optional, with `httpx[cli]`)* -* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* - -A huge amount of credit is due to `requests` for the API layout that -much of this work follows, as well as to `urllib3` for plenty of design -inspiration around the lower-level networking details. - ---- - -HTTPX is BSD licensed code.
Designed & crafted with care.
— 🦋 —