From b1774bae1bde1392944f6befecb507a702ce5aab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E5=AE=A6=E6=88=90?= Date: Mon, 5 Aug 2024 01:01:03 +0800 Subject: [PATCH 001/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20typo=20in=20Chi?= =?UTF-8?q?nese=20translation=20for=20`docs/zh/docs/advanced/testing-depen?= =?UTF-8?q?dencies.md`=20(#11944)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/testing-dependencies.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index dc0f88b33..487f5ebf5 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -22,7 +22,7 @@ ### 使用 `app.dependency_overrides` 属性 -对于这些用例,**FastAPI** 应用支持 `app.dependcy_overrides` 属性,该属性就是**字典**。 +对于这些用例,**FastAPI** 应用支持 `app.dependency_overrides` 属性,该属性就是**字典**。 要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 From 22ffde0356e8b71b5c189b8276a9d51c526060c1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Aug 2024 17:01:24 +0000 Subject: [PATCH 002/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f7a3cbe55..1e2292265 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). From f3e49e5f4e10f7dd0423ce1f9111dd86ef603f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 4 Aug 2024 13:23:14 -0500 Subject: [PATCH 003/356] =?UTF-8?q?=F0=9F=94=87=20Ignore=20warning=20from?= =?UTF-8?q?=20attrs=20in=20Trio=20(#11949)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 3601e6322..c34838b83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -157,7 +157,6 @@ filterwarnings = [ "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - "ignore::trio.TrioDeprecationWarning", # TODO remove pytest-cov 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes @@ -169,6 +168,10 @@ filterwarnings = [ # - https://github.com/mpdavis/python-jose/issues/332 # - https://github.com/mpdavis/python-jose/issues/334 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', + # Trio 24.1.0 raises a warning from attrs + # Ref: https://github.com/python-trio/trio/pull/3054 + # Remove once there's a new version of Trio + 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio', ] [tool.coverage.run] From 35fcb31dca6dbeac5f03bbaea3ae279da9cc0b8a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Aug 2024 18:23:34 +0000 Subject: [PATCH 004/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1e2292265..eb270825b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). * 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian). +### Internal + +* 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.0 ### Breaking Changes From abe62d8a81145e6cce5a5e959cba7f644117d69d Mon Sep 17 00:00:00 2001 From: CAO Mingpei Date: Mon, 5 Aug 2024 07:33:57 +0800 Subject: [PATCH 005/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/query-params.md`=20(#1155?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/query-params.md | 45 +++++++++++++++++++++------ 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index 77138de51..8b2528c9a 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -92,9 +92,19 @@ http://127.0.0.1:8000/items/?skip=20 参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` + +=== "Python 3.10+" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + 本例中,访问: @@ -137,9 +147,18 @@ http://127.0.0.1:8000/items/foo?short=yes FastAPI 通过参数名进行检测: -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + ## 必选查询参数 @@ -195,9 +214,17 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` 本例中有 3 个查询参数: From 9dee1f8b28693cbe59105dc8060e348668485afb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Aug 2024 23:34:17 +0000 Subject: [PATCH 006/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb270825b..f662e59d0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves). From dc384c4f8d6ecfe1b00361a550860a36b87a130f Mon Sep 17 00:00:00 2001 From: "P-E. Brian" Date: Mon, 5 Aug 2024 17:48:45 +0200 Subject: [PATCH 007/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20French=20translati?= =?UTF-8?q?on=20for=20`docs/fr/docs/tutorial/body-multiple-params.md`=20(#?= =?UTF-8?q?11796)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/body-multiple-params.md | 307 ++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 docs/fr/docs/tutorial/body-multiple-params.md diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..563b601f0 --- /dev/null +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -0,0 +1,307 @@ +# Body - Paramètres multiples + +Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body". + +## Mélanger les paramètres `Path`, `Query` et body + +Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire. + +Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : + +=== "Python 3.10+" + + ```Python hl_lines="18-20" + {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="18-20" + {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="17-19" + {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="19-21" + {!> ../../../docs_src/body_multiple_params/tutorial001.py!} + ``` + +!!! note + Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +## Paramètres multiples du body + +Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : + +=== "Python 3.10+" + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial002.py!} + ``` + +Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). + +Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note + "Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. + +Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée). + +## Valeurs scalaires dans le body + +De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`. + +Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`. + +Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). + +Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="20" + {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="22" + {!> ../../../docs_src/body_multiple_params/tutorial003.py!} + ``` + +Dans ce cas, **FastAPI** s'attendra à un body semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc... + +## Paramètres multiples body et query + +Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés. + +Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire : + +```Python +q: Union[str, None] = None +``` + +Ou bien, en Python 3.10 et supérieur : + +```Python +q: str | None = None +``` + +Par exemple : + +=== "Python 3.10+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="28" + {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="25" + {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="27" + {!> ../../../docs_src/body_multiple_params/tutorial004.py!} + ``` + +!!! info + `Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +## Inclure un paramètre imbriqué dans le body + +Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`. + +Par défaut, **FastAPI** attendra sa déclaration directement dans le body. + +Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` : + +```Python +item: Item = Body(embed=True) +``` + +Voici un exemple complet : + +=== "Python 3.10+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="15" + {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Préférez utiliser la version `Annotated` si possible. + + ```Python hl_lines="17" + {!> ../../../docs_src/body_multiple_params/tutorial005.py!} + ``` + +Dans ce cas **FastAPI** attendra un body semblable à : + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +au lieu de : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Pour résumer + +Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body. + +Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé. + +Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body. + +Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré. From af1a07052a713da96c5c75c9548203c77d0b6fd6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 5 Aug 2024 15:49:07 +0000 Subject: [PATCH 008/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f662e59d0..78e27ba7e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus). From 0cd844d3877e6ae9e9fce1c99ea68327254e9b6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 5 Aug 2024 23:48:30 -0500 Subject: [PATCH 009/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20docs=20setup=20?= =?UTF-8?q?with=20latest=20configs=20and=20plugins=20(#11953)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build-docs.yml | 23 +- docs/bn/docs/python-types.md | 303 +++-- docs/de/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../de/docs/advanced/advanced-dependencies.md | 161 ++- docs/de/docs/advanced/async-tests.md | 28 +- docs/de/docs/advanced/behind-a-proxy.md | 51 +- docs/de/docs/advanced/custom-response.md | 87 +- docs/de/docs/advanced/dataclasses.md | 11 +- docs/de/docs/advanced/events.md | 47 +- docs/de/docs/advanced/generate-clients.md | 87 +- docs/de/docs/advanced/index.md | 9 +- docs/de/docs/advanced/middleware.md | 9 +- docs/de/docs/advanced/openapi-callbacks.md | 39 +- docs/de/docs/advanced/openapi-webhooks.md | 14 +- .../path-operation-advanced-configuration.md | 102 +- docs/de/docs/advanced/response-cookies.md | 22 +- docs/de/docs/advanced/response-directly.md | 16 +- docs/de/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 111 +- docs/de/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 724 +++++++---- docs/de/docs/advanced/settings.md | 299 +++-- docs/de/docs/advanced/templates.md | 25 +- docs/de/docs/advanced/testing-dependencies.md | 82 +- docs/de/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/de/docs/advanced/websockets.md | 120 +- docs/de/docs/alternatives.md | 227 ++-- docs/de/docs/async.md | 32 +- docs/de/docs/contributing.md | 177 +-- docs/de/docs/deployment/concepts.md | 34 +- docs/de/docs/deployment/docker.md | 74 +- docs/de/docs/deployment/https.md | 21 +- docs/de/docs/deployment/manually.md | 90 +- docs/de/docs/deployment/server-workers.md | 9 +- docs/de/docs/deployment/versions.md | 14 +- docs/de/docs/external-links.md | 14 +- docs/de/docs/features.md | 9 +- docs/de/docs/help-fastapi.md | 20 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 22 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/de/docs/how-to/extending-openapi.md | 7 +- docs/de/docs/how-to/graphql.md | 18 +- docs/de/docs/how-to/index.md | 7 +- .../docs/how-to/separate-openapi-schemas.md | 211 ++-- docs/de/docs/python-types.md | 303 +++-- docs/de/docs/reference/index.md | 7 +- docs/de/docs/reference/request.md | 7 +- docs/de/docs/reference/websockets.md | 7 +- docs/de/docs/tutorial/background-tasks.md | 64 +- docs/de/docs/tutorial/bigger-applications.md | 181 ++- docs/de/docs/tutorial/body-fields.md | 162 ++- docs/de/docs/tutorial/body-multiple-params.md | 297 +++-- docs/de/docs/tutorial/body-nested-models.md | 297 +++-- docs/de/docs/tutorial/body-updates.md | 171 ++- docs/de/docs/tutorial/body.md | 159 ++- docs/de/docs/tutorial/cookie-params.md | 144 ++- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 222 ++-- .../dependencies/global-dependencies.md | 37 +- docs/de/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/de/docs/tutorial/encoder.md | 27 +- docs/de/docs/tutorial/extra-data-types.md | 128 +- docs/de/docs/tutorial/extra-models.md | 132 +- docs/de/docs/tutorial/first-steps.md | 64 +- docs/de/docs/tutorial/handling-errors.md | 36 +- docs/de/docs/tutorial/header-params.md | 296 +++-- docs/de/docs/tutorial/index.md | 25 +- docs/de/docs/tutorial/metadata.md | 21 +- docs/de/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 356 ++++-- docs/de/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1067 ++++++++++------ docs/de/docs/tutorial/query-params.md | 94 +- docs/de/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/de/docs/tutorial/request-forms.md | 117 +- docs/de/docs/tutorial/response-model.md | 412 ++++--- docs/de/docs/tutorial/response-status-code.md | 46 +- docs/de/docs/tutorial/schema-extra-example.md | 324 +++-- docs/de/docs/tutorial/security/first-steps.md | 180 ++- .../tutorial/security/get-current-user.md | 375 +++--- docs/de/docs/tutorial/security/index.md | 15 +- docs/de/docs/tutorial/security/oauth2-jwt.md | 308 +++-- .../docs/tutorial/security/simple-oauth2.md | 412 ++++--- docs/de/docs/tutorial/static-files.md | 9 +- docs/de/docs/tutorial/testing.md | 109 +- docs/em/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 20 +- .../em/docs/advanced/advanced-dependencies.md | 13 +- docs/em/docs/advanced/async-tests.md | 21 +- docs/em/docs/advanced/behind-a-proxy.md | 51 +- docs/em/docs/advanced/custom-response.md | 87 +- docs/em/docs/advanced/dataclasses.md | 11 +- docs/em/docs/advanced/events.md | 45 +- docs/em/docs/advanced/generate-clients.md | 67 +- docs/em/docs/advanced/index.md | 9 +- docs/em/docs/advanced/middleware.md | 9 +- docs/em/docs/advanced/openapi-callbacks.md | 39 +- .../path-operation-advanced-configuration.md | 48 +- docs/em/docs/advanced/response-cookies.md | 22 +- docs/em/docs/advanced/response-directly.md | 16 +- docs/em/docs/advanced/response-headers.md | 11 +- docs/em/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 77 +- docs/em/docs/advanced/settings.md | 120 +- docs/em/docs/advanced/templates.md | 23 +- docs/em/docs/advanced/testing-database.md | 16 +- docs/em/docs/advanced/testing-dependencies.md | 18 +- docs/em/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/em/docs/advanced/websockets.md | 36 +- docs/em/docs/alternatives.md | 227 ++-- docs/em/docs/async.md | 32 +- docs/em/docs/contributing.md | 124 +- docs/em/docs/deployment/concepts.md | 34 +- docs/em/docs/deployment/docker.md | 74 +- docs/em/docs/deployment/https.md | 21 +- docs/em/docs/deployment/manually.md | 90 +- docs/em/docs/deployment/server-workers.md | 9 +- docs/em/docs/deployment/versions.md | 14 +- docs/em/docs/external-links.md | 7 +- docs/em/docs/features.md | 9 +- docs/em/docs/help-fastapi.md | 20 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/em/docs/how-to/extending-openapi.md | 11 +- docs/em/docs/how-to/graphql.md | 18 +- docs/em/docs/how-to/sql-databases-peewee.md | 141 ++- docs/em/docs/python-types.md | 268 ++-- docs/em/docs/tutorial/background-tasks.md | 20 +- docs/em/docs/tutorial/bigger-applications.md | 144 ++- docs/em/docs/tutorial/body-fields.md | 76 +- docs/em/docs/tutorial/body-multiple-params.md | 120 +- docs/em/docs/tutorial/body-nested-models.md | 297 +++-- docs/em/docs/tutorial/body-updates.md | 153 ++- docs/em/docs/tutorial/body.md | 159 ++- docs/em/docs/tutorial/cookie-params.md | 56 +- docs/em/docs/tutorial/cors.md | 9 +- docs/em/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 20 +- .../dependencies/dependencies-with-yield.md | 93 +- docs/em/docs/tutorial/dependencies/index.md | 83 +- .../tutorial/dependencies/sub-dependencies.md | 80 +- docs/em/docs/tutorial/encoder.md | 27 +- docs/em/docs/tutorial/extra-data-types.md | 40 +- docs/em/docs/tutorial/extra-models.md | 123 +- docs/em/docs/tutorial/first-steps.md | 64 +- docs/em/docs/tutorial/handling-errors.md | 36 +- docs/em/docs/tutorial/header-params.md | 113 +- docs/em/docs/tutorial/index.md | 25 +- docs/em/docs/tutorial/metadata.md | 21 +- docs/em/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 75 +- docs/em/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 359 +++--- docs/em/docs/tutorial/query-params.md | 94 +- docs/em/docs/tutorial/request-files.md | 130 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/em/docs/tutorial/request-forms.md | 43 +- docs/em/docs/tutorial/response-model.md | 403 +++--- docs/em/docs/tutorial/response-status-code.md | 46 +- docs/em/docs/tutorial/schema-extra-example.md | 105 +- docs/em/docs/tutorial/security/first-steps.md | 69 +- .../tutorial/security/get-current-user.md | 118 +- docs/em/docs/tutorial/security/index.md | 15 +- docs/em/docs/tutorial/security/oauth2-jwt.md | 132 +- .../docs/tutorial/security/simple-oauth2.md | 192 +-- docs/em/docs/tutorial/sql-databases.md | 456 ++++--- docs/em/docs/tutorial/static-files.md | 9 +- docs/em/docs/tutorial/testing.md | 65 +- docs/en/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../en/docs/advanced/advanced-dependencies.md | 161 ++- docs/en/docs/advanced/async-tests.md | 28 +- docs/en/docs/advanced/behind-a-proxy.md | 51 +- docs/en/docs/advanced/custom-response.md | 101 +- docs/en/docs/advanced/dataclasses.md | 11 +- docs/en/docs/advanced/events.md | 47 +- docs/en/docs/advanced/generate-clients.md | 87 +- docs/en/docs/advanced/index.md | 9 +- docs/en/docs/advanced/middleware.md | 9 +- docs/en/docs/advanced/openapi-callbacks.md | 39 +- docs/en/docs/advanced/openapi-webhooks.md | 14 +- .../path-operation-advanced-configuration.md | 102 +- docs/en/docs/advanced/response-cookies.md | 22 +- docs/en/docs/advanced/response-directly.md | 16 +- docs/en/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 111 +- docs/en/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 724 +++++++---- docs/en/docs/advanced/settings.md | 299 +++-- docs/en/docs/advanced/templates.md | 25 +- docs/en/docs/advanced/testing-database.md | 27 +- docs/en/docs/advanced/testing-dependencies.md | 82 +- docs/en/docs/advanced/testing-websockets.md | 7 +- .../docs/advanced/using-request-directly.md | 20 +- docs/en/docs/advanced/websockets.md | 120 +- docs/en/docs/alternatives.md | 227 ++-- docs/en/docs/async.md | 32 +- docs/en/docs/contributing.md | 177 +-- docs/en/docs/deployment/concepts.md | 34 +- docs/en/docs/deployment/docker.md | 72 +- docs/en/docs/deployment/https.md | 21 +- docs/en/docs/deployment/manually.md | 111 +- docs/en/docs/deployment/server-workers.md | 9 +- docs/en/docs/deployment/versions.md | 14 +- docs/en/docs/external-links.md | 7 +- docs/en/docs/fastapi-cli.md | 7 +- docs/en/docs/fastapi-people.md | 9 +- docs/en/docs/features.md | 9 +- docs/en/docs/help-fastapi.md | 20 +- .../docs/how-to/async-sql-encode-databases.md | 66 +- docs/en/docs/how-to/custom-docs-ui-assets.md | 22 +- .../docs/how-to/custom-request-and-route.md | 40 +- docs/en/docs/how-to/extending-openapi.md | 7 +- docs/en/docs/how-to/graphql.md | 18 +- docs/en/docs/how-to/index.md | 6 +- .../docs/how-to/nosql-databases-couchbase.md | 34 +- .../docs/how-to/separate-openapi-schemas.md | 211 ++-- docs/en/docs/how-to/sql-databases-peewee.md | 161 ++- docs/en/docs/js/custom.js | 7 +- docs/en/docs/management-tasks.md | 67 +- docs/en/docs/newsletter.md | 2 +- docs/en/docs/python-types.md | 303 +++-- docs/en/docs/reference/request.md | 7 +- docs/en/docs/reference/websockets.md | 7 +- docs/en/docs/tutorial/background-tasks.md | 64 +- docs/en/docs/tutorial/bigger-applications.md | 181 ++- docs/en/docs/tutorial/body-fields.md | 164 ++- docs/en/docs/tutorial/body-multiple-params.md | 296 +++-- docs/en/docs/tutorial/body-nested-models.md | 297 +++-- docs/en/docs/tutorial/body-updates.md | 171 ++- docs/en/docs/tutorial/body.md | 159 ++- docs/en/docs/tutorial/cookie-params.md | 144 ++- docs/en/docs/tutorial/cors.md | 9 +- docs/en/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 295 +++-- .../dependencies/global-dependencies.md | 37 +- docs/en/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/en/docs/tutorial/encoder.md | 27 +- docs/en/docs/tutorial/extra-data-types.md | 128 +- docs/en/docs/tutorial/extra-models.md | 132 +- docs/en/docs/tutorial/first-steps.md | 51 +- docs/en/docs/tutorial/handling-errors.md | 36 +- docs/en/docs/tutorial/header-params.md | 296 +++-- docs/en/docs/tutorial/index.md | 9 +- docs/en/docs/tutorial/metadata.md | 21 +- docs/en/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 352 ++++-- docs/en/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1073 ++++++++++------ docs/en/docs/tutorial/query-params.md | 94 +- docs/en/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/en/docs/tutorial/request-forms.md | 117 +- docs/en/docs/tutorial/response-model.md | 412 ++++--- docs/en/docs/tutorial/response-status-code.md | 46 +- docs/en/docs/tutorial/schema-extra-example.md | 324 +++-- docs/en/docs/tutorial/security/first-steps.md | 181 ++- .../tutorial/security/get-current-user.md | 375 +++--- docs/en/docs/tutorial/security/index.md | 15 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 308 +++-- .../docs/tutorial/security/simple-oauth2.md | 412 ++++--- docs/en/docs/tutorial/sql-databases.md | 476 +++++--- docs/en/docs/tutorial/static-files.md | 9 +- docs/en/docs/tutorial/testing.md | 109 +- docs/en/mkdocs.insiders.yml | 5 + docs/en/mkdocs.yml | 109 +- .../docs/advanced/additional-status-codes.md | 20 +- docs/es/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 23 +- docs/es/docs/advanced/response-directly.md | 16 +- docs/es/docs/advanced/response-headers.md | 11 +- docs/es/docs/advanced/security/index.md | 9 +- docs/es/docs/async.md | 32 +- docs/es/docs/deployment/versions.md | 14 +- docs/es/docs/external-links.md | 7 +- docs/es/docs/features.md | 9 +- docs/es/docs/how-to/graphql.md | 18 +- docs/es/docs/python-types.md | 21 +- docs/es/docs/tutorial/cookie-params.md | 144 ++- docs/es/docs/tutorial/first-steps.md | 64 +- docs/es/docs/tutorial/index.md | 25 +- docs/es/docs/tutorial/path-params.md | 66 +- docs/es/docs/tutorial/query-params.md | 23 +- docs/fa/docs/features.md | 9 +- docs/fa/docs/tutorial/middleware.md | 24 +- docs/fa/docs/tutorial/security/index.md | 16 +- docs/fr/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 20 +- docs/fr/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 46 +- docs/fr/docs/advanced/response-directly.md | 16 +- docs/fr/docs/alternatives.md | 182 ++- docs/fr/docs/async.md | 32 +- docs/fr/docs/contributing.md | 158 ++- docs/fr/docs/deployment/docker.md | 7 +- docs/fr/docs/deployment/https.md | 7 +- docs/fr/docs/deployment/manually.md | 90 +- docs/fr/docs/deployment/versions.md | 14 +- docs/fr/docs/external-links.md | 7 +- docs/fr/docs/features.md | 9 +- docs/fr/docs/python-types.md | 30 +- docs/fr/docs/tutorial/body-multiple-params.md | 297 +++-- docs/fr/docs/tutorial/body.md | 39 +- docs/fr/docs/tutorial/debugging.md | 5 +- docs/fr/docs/tutorial/first-steps.md | 63 +- docs/fr/docs/tutorial/index.md | 25 +- .../path-params-numeric-validations.md | 389 +++--- docs/fr/docs/tutorial/path-params.md | 72 +- .../tutorial/query-params-str-validations.md | 73 +- docs/fr/docs/tutorial/query-params.md | 22 +- docs/hu/docs/index.md | 2 +- docs/id/docs/tutorial/index.md | 25 +- docs/it/docs/index.md | 1 - .../docs/advanced/additional-status-codes.md | 20 +- docs/ja/docs/advanced/custom-response.md | 87 +- docs/ja/docs/advanced/index.md | 9 +- .../path-operation-advanced-configuration.md | 23 +- docs/ja/docs/advanced/response-directly.md | 16 +- docs/ja/docs/advanced/websockets.md | 38 +- docs/ja/docs/alternatives.md | 229 ++-- docs/ja/docs/async.md | 18 +- docs/ja/docs/contributing.md | 124 +- docs/ja/docs/deployment/concepts.md | 38 +- docs/ja/docs/deployment/docker.md | 76 +- docs/ja/docs/deployment/https.md | 21 +- docs/ja/docs/deployment/manually.md | 79 +- docs/ja/docs/deployment/server-workers.md | 11 +- docs/ja/docs/deployment/versions.md | 14 +- docs/ja/docs/external-links.md | 7 +- docs/ja/docs/features.md | 9 +- docs/ja/docs/python-types.md | 30 +- docs/ja/docs/tutorial/body-fields.md | 27 +- docs/ja/docs/tutorial/body-multiple-params.md | 20 +- docs/ja/docs/tutorial/body-nested-models.md | 27 +- docs/ja/docs/tutorial/body-updates.md | 33 +- docs/ja/docs/tutorial/body.md | 39 +- docs/ja/docs/tutorial/cookie-params.md | 16 +- docs/ja/docs/tutorial/cors.md | 9 +- docs/ja/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 9 +- ...pendencies-in-path-operation-decorators.md | 11 +- .../dependencies/dependencies-with-yield.md | 108 +- docs/ja/docs/tutorial/dependencies/index.md | 23 +- .../tutorial/dependencies/sub-dependencies.md | 20 +- docs/ja/docs/tutorial/encoder.md | 7 +- docs/ja/docs/tutorial/extra-models.md | 16 +- docs/ja/docs/tutorial/first-steps.md | 64 +- docs/ja/docs/tutorial/handling-errors.md | 36 +- docs/ja/docs/tutorial/header-params.md | 22 +- docs/ja/docs/tutorial/index.md | 25 +- docs/ja/docs/tutorial/metadata.md | 14 +- docs/ja/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 32 +- .../path-params-numeric-validations.md | 35 +- docs/ja/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 74 +- docs/ja/docs/tutorial/query-params.md | 14 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/ja/docs/tutorial/request-forms.md | 43 +- docs/ja/docs/tutorial/response-model.md | 70 +- docs/ja/docs/tutorial/response-status-code.md | 46 +- docs/ja/docs/tutorial/schema-extra-example.md | 7 +- docs/ja/docs/tutorial/security/first-steps.md | 69 +- .../tutorial/security/get-current-user.md | 16 +- docs/ja/docs/tutorial/security/index.md | 15 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 51 +- docs/ja/docs/tutorial/static-files.md | 9 +- docs/ja/docs/tutorial/testing.md | 56 +- docs/ko/docs/advanced/events.md | 32 +- docs/ko/docs/advanced/index.md | 9 +- docs/ko/docs/async.md | 18 +- docs/ko/docs/deployment/docker.md | 74 +- docs/ko/docs/deployment/server-workers.md | 9 +- docs/ko/docs/deployment/versions.md | 14 +- docs/ko/docs/features.md | 9 +- docs/ko/docs/python-types.md | 29 +- docs/ko/docs/tutorial/background-tasks.md | 20 +- docs/ko/docs/tutorial/body-fields.md | 164 ++- docs/ko/docs/tutorial/body-multiple-params.md | 21 +- docs/ko/docs/tutorial/body-nested-models.md | 27 +- docs/ko/docs/tutorial/body.md | 159 ++- docs/ko/docs/tutorial/cookie-params.md | 144 ++- docs/ko/docs/tutorial/cors.md | 9 +- docs/ko/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/global-dependencies.md | 37 +- docs/ko/docs/tutorial/dependencies/index.md | 265 ++-- docs/ko/docs/tutorial/encoder.md | 7 +- docs/ko/docs/tutorial/extra-data-types.md | 128 +- docs/ko/docs/tutorial/first-steps.md | 64 +- docs/ko/docs/tutorial/header-params.md | 23 +- docs/ko/docs/tutorial/index.md | 25 +- docs/ko/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 32 +- .../path-params-numeric-validations.md | 35 +- docs/ko/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 73 +- docs/ko/docs/tutorial/query-params.md | 23 +- docs/ko/docs/tutorial/request-files.md | 81 +- .../docs/tutorial/request-forms-and-files.md | 18 +- docs/ko/docs/tutorial/response-model.md | 70 +- docs/ko/docs/tutorial/response-status-code.md | 46 +- docs/ko/docs/tutorial/schema-extra-example.md | 324 +++-- .../tutorial/security/get-current-user.md | 118 +- .../docs/tutorial/security/simple-oauth2.md | 192 +-- docs/ko/docs/tutorial/static-files.md | 9 +- docs/missing-translation.md | 9 +- docs/pl/docs/features.md | 9 +- docs/pl/docs/help-fastapi.md | 20 +- docs/pl/docs/tutorial/first-steps.md | 63 +- docs/pl/docs/tutorial/index.md | 25 +- docs/pt/docs/advanced/additional-responses.md | 51 +- .../docs/advanced/additional-status-codes.md | 84 +- .../pt/docs/advanced/advanced-dependencies.md | 161 ++- docs/pt/docs/advanced/async-tests.md | 28 +- docs/pt/docs/advanced/behind-a-proxy.md | 51 +- docs/pt/docs/advanced/events.md | 47 +- docs/pt/docs/advanced/index.md | 9 +- docs/pt/docs/advanced/openapi-webhooks.md | 14 +- docs/pt/docs/advanced/settings.md | 299 +++-- docs/pt/docs/advanced/templates.md | 23 +- docs/pt/docs/alternatives.md | 231 ++-- docs/pt/docs/async.md | 18 +- docs/pt/docs/contributing.md | 124 +- docs/pt/docs/deployment.md | 98 +- docs/pt/docs/deployment/docker.md | 73 +- docs/pt/docs/deployment/https.md | 7 +- docs/pt/docs/deployment/versions.md | 14 +- docs/pt/docs/external-links.md | 7 +- docs/pt/docs/fastapi-cli.md | 7 +- docs/pt/docs/features.md | 9 +- docs/pt/docs/help-fastapi.md | 9 +- docs/pt/docs/how-to/index.md | 6 +- docs/pt/docs/python-types.md | 29 +- docs/pt/docs/tutorial/body-fields.md | 27 +- docs/pt/docs/tutorial/body-multiple-params.md | 120 +- docs/pt/docs/tutorial/body-nested-models.md | 27 +- docs/pt/docs/tutorial/body.md | 39 +- docs/pt/docs/tutorial/cookie-params.md | 16 +- docs/pt/docs/tutorial/cors.md | 9 +- .../dependencies/classes-as-dependencies.md | 603 +++++---- ...pendencies-in-path-operation-decorators.md | 171 ++- .../dependencies/dependencies-with-yield.md | 296 +++-- .../dependencies/global-dependencies.md | 37 +- docs/pt/docs/tutorial/dependencies/index.md | 265 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/pt/docs/tutorial/encoder.md | 27 +- docs/pt/docs/tutorial/extra-models.md | 123 +- docs/pt/docs/tutorial/first-steps.md | 64 +- docs/pt/docs/tutorial/handling-errors.md | 34 +- docs/pt/docs/tutorial/header-params.md | 113 +- docs/pt/docs/tutorial/index.md | 25 +- docs/pt/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 75 +- docs/pt/docs/tutorial/path-params.md | 56 +- .../tutorial/query-params-str-validations.md | 73 +- docs/pt/docs/tutorial/query-params.md | 93 +- .../docs/tutorial/request-forms-and-files.md | 17 +- docs/pt/docs/tutorial/request-forms.md | 43 +- docs/pt/docs/tutorial/response-status-code.md | 45 +- docs/pt/docs/tutorial/schema-extra-example.md | 25 +- docs/pt/docs/tutorial/security/first-steps.md | 49 +- docs/pt/docs/tutorial/security/index.md | 15 +- docs/pt/docs/tutorial/static-files.md | 9 +- docs/ru/docs/alternatives.md | 241 ++-- docs/ru/docs/async.md | 22 +- docs/ru/docs/contributing.md | 123 +- docs/ru/docs/deployment/concepts.md | 34 +- docs/ru/docs/deployment/docker.md | 74 +- docs/ru/docs/deployment/https.md | 21 +- docs/ru/docs/deployment/manually.md | 89 +- docs/ru/docs/deployment/versions.md | 14 +- docs/ru/docs/external-links.md | 7 +- docs/ru/docs/features.md | 9 +- docs/ru/docs/help-fastapi.md | 20 +- docs/ru/docs/python-types.md | 30 +- docs/ru/docs/tutorial/background-tasks.md | 20 +- docs/ru/docs/tutorial/body-fields.md | 76 +- docs/ru/docs/tutorial/body-multiple-params.md | 296 +++-- docs/ru/docs/tutorial/body-nested-models.md | 297 +++-- docs/ru/docs/tutorial/body-updates.md | 153 ++- docs/ru/docs/tutorial/body.md | 39 +- docs/ru/docs/tutorial/cookie-params.md | 56 +- docs/ru/docs/tutorial/cors.md | 9 +- docs/ru/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 619 ++++++---- ...pendencies-in-path-operation-decorators.md | 168 ++- .../dependencies/dependencies-with-yield.md | 182 ++- .../dependencies/global-dependencies.md | 37 +- docs/ru/docs/tutorial/dependencies/index.md | 262 ++-- .../tutorial/dependencies/sub-dependencies.md | 243 ++-- docs/ru/docs/tutorial/encoder.md | 27 +- docs/ru/docs/tutorial/extra-data-types.md | 40 +- docs/ru/docs/tutorial/extra-models.md | 123 +- docs/ru/docs/tutorial/first-steps.md | 64 +- docs/ru/docs/tutorial/handling-errors.md | 36 +- docs/ru/docs/tutorial/header-params.md | 296 +++-- docs/ru/docs/tutorial/index.md | 25 +- docs/ru/docs/tutorial/metadata.md | 21 +- .../tutorial/path-operation-configuration.md | 182 +-- .../path-params-numeric-validations.md | 354 ++++-- docs/ru/docs/tutorial/path-params.md | 66 +- .../tutorial/query-params-str-validations.md | 1083 ++++++++++------- docs/ru/docs/tutorial/query-params.md | 94 +- docs/ru/docs/tutorial/request-files.md | 390 +++--- .../docs/tutorial/request-forms-and-files.md | 92 +- docs/ru/docs/tutorial/request-forms.md | 117 +- docs/ru/docs/tutorial/response-model.md | 403 +++--- docs/ru/docs/tutorial/response-status-code.md | 46 +- docs/ru/docs/tutorial/schema-extra-example.md | 193 +-- docs/ru/docs/tutorial/security/first-steps.md | 177 ++- docs/ru/docs/tutorial/security/index.md | 15 +- docs/ru/docs/tutorial/static-files.md | 9 +- docs/ru/docs/tutorial/testing.md | 109 +- docs/tr/docs/advanced/index.md | 9 +- docs/tr/docs/advanced/security/index.md | 9 +- docs/tr/docs/advanced/testing-websockets.md | 7 +- docs/tr/docs/alternatives.md | 230 ++-- docs/tr/docs/async.md | 18 +- docs/tr/docs/external-links.md | 7 +- docs/tr/docs/features.md | 9 +- docs/tr/docs/how-to/index.md | 6 +- docs/tr/docs/python-types.md | 30 +- docs/tr/docs/tutorial/cookie-params.md | 144 ++- docs/tr/docs/tutorial/first-steps.md | 64 +- docs/tr/docs/tutorial/path-params.md | 66 +- docs/tr/docs/tutorial/query-params.md | 94 +- docs/tr/docs/tutorial/request-forms.md | 117 +- docs/tr/docs/tutorial/static-files.md | 9 +- docs/uk/docs/alternatives.md | 225 ++-- docs/uk/docs/python-types.md | 261 ++-- docs/uk/docs/tutorial/body-fields.md | 164 ++- docs/uk/docs/tutorial/body.md | 159 ++- docs/uk/docs/tutorial/cookie-params.md | 144 ++- docs/uk/docs/tutorial/encoder.md | 27 +- docs/uk/docs/tutorial/extra-data-types.md | 128 +- docs/uk/docs/tutorial/first-steps.md | 50 +- docs/uk/docs/tutorial/index.md | 25 +- docs/vi/docs/features.md | 9 +- docs/vi/docs/python-types.md | 302 +++-- docs/vi/docs/tutorial/first-steps.md | 64 +- docs/vi/docs/tutorial/index.md | 25 +- docs/zh-hant/docs/benchmarks.md | 68 +- docs/zh-hant/docs/fastapi-people.md | 9 +- docs/zh/docs/advanced/additional-responses.md | 40 +- .../docs/advanced/additional-status-codes.md | 20 +- .../zh/docs/advanced/advanced-dependencies.md | 12 +- docs/zh/docs/advanced/behind-a-proxy.md | 44 +- docs/zh/docs/advanced/custom-response.md | 78 +- docs/zh/docs/advanced/dataclasses.md | 10 +- docs/zh/docs/advanced/events.md | 30 +- docs/zh/docs/advanced/generate-clients.md | 67 +- docs/zh/docs/advanced/index.md | 9 +- docs/zh/docs/advanced/middleware.md | 8 +- docs/zh/docs/advanced/openapi-callbacks.md | 34 +- .../path-operation-advanced-configuration.md | 23 +- docs/zh/docs/advanced/response-cookies.md | 22 +- docs/zh/docs/advanced/response-directly.md | 16 +- docs/zh/docs/advanced/response-headers.md | 11 +- .../docs/advanced/security/http-basic-auth.md | 112 +- docs/zh/docs/advanced/security/index.md | 9 +- .../docs/advanced/security/oauth2-scopes.md | 70 +- docs/zh/docs/advanced/settings.md | 232 ++-- docs/zh/docs/advanced/templates.md | 22 +- docs/zh/docs/advanced/testing-database.md | 14 +- docs/zh/docs/advanced/testing-dependencies.md | 16 +- docs/zh/docs/advanced/testing-websockets.md | 6 +- .../docs/advanced/using-request-directly.md | 18 +- docs/zh/docs/advanced/websockets.md | 120 +- docs/zh/docs/async.md | 32 +- docs/zh/docs/contributing.md | 177 +-- docs/zh/docs/deployment/concepts.md | 29 +- docs/zh/docs/deployment/docker.md | 73 +- docs/zh/docs/deployment/https.md | 14 +- docs/zh/docs/deployment/manually.md | 88 +- docs/zh/docs/deployment/server-workers.md | 7 +- docs/zh/docs/deployment/versions.md | 14 +- docs/zh/docs/fastapi-cli.md | 7 +- docs/zh/docs/fastapi-people.md | 9 +- docs/zh/docs/features.md | 9 +- docs/zh/docs/help-fastapi.md | 8 +- docs/zh/docs/how-to/index.md | 6 +- docs/zh/docs/python-types.md | 21 +- docs/zh/docs/tutorial/background-tasks.md | 64 +- docs/zh/docs/tutorial/bigger-applications.md | 144 ++- docs/zh/docs/tutorial/body-fields.md | 152 ++- docs/zh/docs/tutorial/body-multiple-params.md | 295 +++-- docs/zh/docs/tutorial/body-nested-models.md | 297 +++-- docs/zh/docs/tutorial/body-updates.md | 30 +- docs/zh/docs/tutorial/body.md | 156 ++- docs/zh/docs/tutorial/cookie-params.md | 142 ++- docs/zh/docs/tutorial/cors.md | 9 +- docs/zh/docs/tutorial/debugging.md | 7 +- .../dependencies/classes-as-dependencies.md | 149 ++- ...pendencies-in-path-operation-decorators.md | 18 +- .../dependencies/dependencies-with-yield.md | 157 ++- docs/zh/docs/tutorial/dependencies/index.md | 20 +- .../tutorial/dependencies/sub-dependencies.md | 18 +- docs/zh/docs/tutorial/encoder.md | 27 +- docs/zh/docs/tutorial/extra-data-types.md | 128 +- docs/zh/docs/tutorial/extra-models.md | 120 +- docs/zh/docs/tutorial/first-steps.md | 63 +- docs/zh/docs/tutorial/handling-errors.md | 28 +- docs/zh/docs/tutorial/header-params.md | 292 +++-- docs/zh/docs/tutorial/index.md | 25 +- docs/zh/docs/tutorial/metadata.md | 211 ++-- docs/zh/docs/tutorial/middleware.md | 27 +- .../tutorial/path-operation-configuration.md | 28 +- .../path-params-numeric-validations.md | 180 ++- docs/zh/docs/tutorial/path-params.md | 58 +- .../tutorial/query-params-str-validations.md | 74 +- docs/zh/docs/tutorial/query-params.md | 98 +- docs/zh/docs/tutorial/request-files.md | 122 +- .../docs/tutorial/request-forms-and-files.md | 16 +- docs/zh/docs/tutorial/request-forms.md | 38 +- docs/zh/docs/tutorial/response-model.md | 160 ++- docs/zh/docs/tutorial/response-status-code.md | 40 +- docs/zh/docs/tutorial/schema-extra-example.md | 111 +- docs/zh/docs/tutorial/security/first-steps.md | 99 +- .../tutorial/security/get-current-user.md | 15 +- docs/zh/docs/tutorial/security/index.md | 15 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 238 ++-- .../docs/tutorial/security/simple-oauth2.md | 84 +- docs/zh/docs/tutorial/sql-databases.md | 465 ++++--- docs/zh/docs/tutorial/static-files.md | 9 +- docs/zh/docs/tutorial/testing.md | 109 +- requirements-docs-insiders.txt | 3 + requirements-docs.txt | 8 +- scripts/docs.py | 19 +- 643 files changed, 37192 insertions(+), 21693 deletions(-) create mode 100644 requirements-docs-insiders.txt diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 262c7fa5c..e46629e9b 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -18,7 +18,7 @@ jobs: docs: ${{ steps.filter.outputs.docs }} steps: - uses: actions/checkout@v4 - # For pull requests it's not necessary to checkout the code but for master it is + # For pull requests it's not necessary to checkout the code but for the main branch it is - uses: dorny/paths-filter@v3 id: filter with: @@ -28,9 +28,12 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - requirements-docs-insiders.txt - pyproject.toml - mkdocs.yml - mkdocs.insiders.yml + - mkdocs.maybe-insiders.yml + - mkdocs.no-insiders.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml langs: @@ -49,17 +52,16 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + run: pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Verify Docs run: python ./scripts/docs.py verify-docs - name: Export Language Codes @@ -90,16 +92,15 @@ jobs: id: cache with: path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08 + key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 - name: Install docs extras if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + run: pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Update Languages run: python ./scripts/docs.py update-languages - uses: actions/cache@v4 diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index 6923363dd..d5304a65e 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -12,8 +12,11 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে। -!!! Note - যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। +/// note + +যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। + +/// ## প্রেরণা @@ -170,45 +173,55 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক। -=== "Python 3.9+" +//// tab | Python 3.9+ - ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। - টাইপ হিসেবে, `list` ব্যবহার করুন। +টাইপ হিসেবে, `list` ব্যবহার করুন। - যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: +//// tab | Python 3.8+ - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: - ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। +``` Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: +//// - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +/// info -!!! Info - স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। +স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। - এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। +এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। + +/// এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।" -!!! Tip - যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। +/// tip + +যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। + +/// এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে: @@ -224,17 +237,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// এর মানে হল: @@ -249,18 +266,21 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` +//// এর মানে হল: @@ -276,17 +296,21 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন। -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`। @@ -306,23 +330,29 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ বিকল্প" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// + +//// tab | Python 3.8+ বিকল্প + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### `Union` বা `Optional` ব্যবহার @@ -367,46 +397,53 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন: -=== "Python 3.10+" - আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): +//// tab | Python 3.10+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (Python 3.8 এর মতোই) +* ...এবং অন্যান্য। - এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: +Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। - * `Union` - * `Optional` (Python 3.8 এর মতোই) - * ...এবং অন্যান্য। +//// - Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। +//// tab | Python 3.9+ -=== "Python 3.9+" +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): - আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: - এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: +* `Union` +* `Optional` +* ...এবং অন্যান্য। - * `Union` - * `Optional` - * ...এবং অন্যান্য। +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...এবং অন্যান্য। +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// ### ক্লাস হিসেবে টাইপস @@ -446,55 +483,71 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। -!!! Info - [Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। +/// **FastAPI** মূলত Pydantic-এর উপর নির্মিত। আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)। -!!! Tip - যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। +/// tip + +যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। + +/// ## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়। -=== "Python 3.9+" +//// tab | Python 3.9+ + +Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। - Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। +এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। - এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`। @@ -506,10 +559,13 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে। -!!! Tip - এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ +/// tip - এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 +এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ + +এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 + +/// ## **FastAPI**-এ টাইপ হিন্টস @@ -533,5 +589,8 @@ Python নিজে এই `Annotated` দিয়ে কিছুই করে গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে। -!!! Info - যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। +/// info + +যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। + +/// diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 2bfcfab33..6f2c4b2dd 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Zusätzliche Responses in OpenAPI -!!! warning "Achtung" - Dies ist ein eher fortgeschrittenes Thema. +/// warning | "Achtung" - Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. +Dies ist ein eher fortgeschrittenes Thema. + +Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +/// Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. @@ -27,20 +30,26 @@ Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydan {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. +/// note | "Hinweis" + +Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +/// + +/// info -!!! info - Der `model`-Schlüssel ist nicht Teil von OpenAPI. +Der `model`-Schlüssel ist nicht Teil von OpenAPI. - **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. +**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. - Die richtige Stelle ist: +Die richtige Stelle ist: - * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: - * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: - * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. - * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. +* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. + +/// Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: @@ -172,13 +181,19 @@ Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. +/// note | "Hinweis" + +Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +/// + +/// info + +Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). -!!! info - Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). +Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. - Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. +/// ## Informationen kombinieren diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index e9de267cf..672efee51 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! warning "Achtung" - Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. +/// - Sie wird nicht mit einem Modell usw. serialisiert. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). +//// -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +//// tab | Python 3.8+ nicht annotiert - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | "Achtung" + +Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. + +Sie wird nicht mit einem Modell usw. serialisiert. + +Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). + +/// + +/// note | "Technische Details" + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. + +/// ## OpenAPI- und API-Dokumentation diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 33b93b332..f29970872 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -45,26 +54,35 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -72,26 +90,35 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. -!!! tip "Tipp" - Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. +Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. - Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. +In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. - In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. +Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. - Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. +/// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 2e2c22210..9f0bd4aa2 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynch {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. +/// tip | "Tipp" + +Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. + +/// Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. @@ -81,15 +84,24 @@ response = client.get('/') ... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. -!!! tip "Tipp" - Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. +/// tip | "Tipp" + +Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. + +/// -!!! warning "Achtung" - Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. +/// warning | "Achtung" + +Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. + +/// ## Andere asynchrone Funktionsaufrufe Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. -!!! tip "Tipp" - Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. +/// tip | "Tipp" + +Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. + +/// diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index ad0a92e28..18f90ebde 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip "Tipp" - Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. +/// tip | "Tipp" + +Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +/// Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: @@ -81,10 +84,13 @@ $ uvicorn main:app --root-path /api/v1 Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. -!!! note "Technische Details" - Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. +/// note | "Technische Details" + +Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + +Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. - Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. +/// ### Überprüfen des aktuellen `root_path` @@ -172,8 +178,11 @@ Dann erstellen Sie eine Datei `traefik.toml` mit: Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. -!!! tip "Tipp" - Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. +/// tip | "Tipp" + +Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +/// Erstellen Sie nun die andere Datei `routes.toml`: @@ -239,8 +248,11 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:9999/api/v1/app. @@ -283,8 +295,11 @@ Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`ser ## Zusätzliche Server -!!! warning "Achtung" - Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. +/// warning | "Achtung" + +Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +/// Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. @@ -323,15 +338,21 @@ Erzeugt ein OpenAPI-Schema, wie: } ``` -!!! tip "Tipp" - Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. +/// tip | "Tipp" + +Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +/// In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen: -!!! tip "Tipp" - Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. +/// tip | "Tipp" + +Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +/// ### Den automatischen Server von `root_path` deaktivieren diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 68c037ad7..20d6a039a 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. -!!! note "Hinweis" - Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. +/// note | "Hinweis" + +Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. + +/// ## `ORJSONResponse` verwenden @@ -31,15 +34,21 @@ Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSO {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info + +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + +In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// - In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. +/// tip | "Tipp" - Und er wird als solcher in OpenAPI dokumentiert. +Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. -!!! tip "Tipp" - Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. +/// ## HTML-Response @@ -52,12 +61,15 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info - In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. - Und er wird als solcher in OpenAPI dokumentiert. +In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// ### Eine `Response` zurückgeben @@ -69,11 +81,17 @@ Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so a {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "Achtung" - Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. +/// warning | "Achtung" + +Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. + +/// + +/// info -!!! info - Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. +Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. + +/// ### In OpenAPI dokumentieren und `Response` überschreiben @@ -103,10 +121,13 @@ Hier sind einige der verfügbaren Responses. Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. -!!! note "Technische Details" - Sie können auch `from starlette.responses import HTMLResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### `Response` @@ -153,15 +174,21 @@ Eine schnelle alternative JSON-Response mit `ujson`. -!!! warning "Achtung" - `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. +/// warning | "Achtung" + +`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "Tipp" - Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. +/// tip | "Tipp" + +Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. + +/// ### `RedirectResponse` @@ -222,8 +249,11 @@ Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbei Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. -!!! tip "Tipp" - Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. +/// tip | "Tipp" + +Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. + +/// ### `FileResponse` @@ -292,8 +322,11 @@ Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "Tipp" - Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. +/// tip | "Tipp" + +Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. + +/// ## Zusätzliche Dokumentation diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index c78a6d3dd..d5a663485 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ Und natürlich wird das gleiche unterstützt: Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. -!!! info - Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. +/// info - Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. +Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. - Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 +Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + +Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +/// ## Datenklassen als `response_model` diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index e29f61ab9..e898db49b 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -38,10 +38,13 @@ Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. -!!! tip "Tipp" - Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. +/// tip | "Tipp" - Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 +Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + +Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +/// ### Lifespan-Funktion @@ -91,10 +94,13 @@ Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontext ## Alternative Events (deprecated) -!!! warning "Achtung" - Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. +/// warning | "Achtung" + +Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. - Sie können diesen Teil wahrscheinlich überspringen. +Sie können diesen Teil wahrscheinlich überspringen. + +/// Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. @@ -126,17 +132,23 @@ Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführ Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. -!!! info - In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. +/// info + +In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. +/// - Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. +/// tip | "Tipp" - Aber `open()` verwendet nicht `async` und `await`. +Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. - Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. +Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + +Aber `open()` verwendet nicht `async` und `await`. + +Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +/// ### `startup` und `shutdown` zusammen @@ -152,10 +164,13 @@ Nur ein technisches Detail für die neugierigen Nerds. 🤓 In der technischen ASGI-Spezifikation ist dies Teil des Lifespan Protokolls und definiert Events namens `startup` und `shutdown`. -!!! info - Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. +/// info + +Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. + +Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. - Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. +/// ## Unteranwendungen diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index d69437954..b8d66fdd7 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -28,17 +28,21 @@ Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und d Beginnen wir mit einer einfachen FastAPI-Anwendung: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -123,8 +127,11 @@ Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payl -!!! tip "Tipp" - Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. +/// tip | "Tipp" + +Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. + +/// Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten: @@ -140,17 +147,21 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### Einen TypeScript-Client mit Tags generieren @@ -197,17 +208,21 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -229,17 +244,21 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../../docs_src/generate_clients/tutorial004.js!} +``` - ```Javascript - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann. diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md index 048e31e06..953ad317d 100644 --- a/docs/de/docs/advanced/index.md +++ b/docs/de/docs/advanced/index.md @@ -6,10 +6,13 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | "Tipp" - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 2c4e8542a..4116b30ec 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. -!!! note "Technische Details" - Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. +/// note | "Technische Details" - **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. +Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + +**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 026fdb4fe..d7b5bc885 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrschei {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. +/// tip | "Tipp" + +Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. + +/// Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. @@ -61,10 +64,13 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. -!!! tip "Tipp" - Der eigentliche Callback ist nur ein HTTP-Request. +/// tip | "Tipp" + +Der eigentliche Callback ist nur ein HTTP-Request. - Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. +Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. + +/// ## Schreiben des Codes, der den Callback dokumentiert @@ -74,10 +80,13 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). -!!! tip "Tipp" - Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. +/// tip | "Tipp" + +Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. - Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. +Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +/// ### Einen Callback-`APIRouter` erstellen @@ -154,8 +163,11 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d } ``` -!!! tip "Tipp" - Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). +/// tip | "Tipp" + +Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +/// ### Den Callback-Router hinzufügen @@ -167,8 +179,11 @@ Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer AP {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. +/// tip | "Tipp" + +Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +/// ### Es in der Dokumentation ansehen diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 339218080..fb0daa908 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren. -!!! info - Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. +/// info + +Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. + +/// ## Eine Anwendung mit Webhooks @@ -35,8 +38,11 @@ Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. -!!! info - Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. +/// info + +Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. + +/// Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 406a08e9e..c9cb82fe3 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "Achtung" - Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. +/// warning | "Achtung" + +Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +/// Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. @@ -23,13 +26,19 @@ Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Tipp" - Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. +/// tip | "Tipp" + +Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +/// + +/// warning | "Achtung" + +Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. -!!! warning "Achtung" - Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. +Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. - Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. +/// ## Von OpenAPI ausschließen @@ -65,8 +74,11 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. -!!! note "Technische Details" - In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. +/// note | "Technische Details" + +In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. + +/// Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. @@ -74,10 +86,13 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. -!!! tip "Tipp" - Dies ist ein Low-Level Erweiterungspunkt. +/// tip | "Tipp" + +Dies ist ein Low-Level Erweiterungspunkt. - Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. +Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +/// Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. @@ -150,20 +165,27 @@ Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. -!!! info - In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. +/// Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. @@ -171,22 +193,32 @@ Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip | "Tipp" -!!! info - In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. +Hier verwenden wir dasselbe Pydantic-Modell wieder. -!!! tip "Tipp" - Hier verwenden wir dasselbe Pydantic-Modell wieder. +Aber genauso hätten wir es auch auf andere Weise validieren können. - Aber genauso hätten wir es auch auf andere Weise validieren können. +/// diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 0f09bd444..3d2043565 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ Setzen Sie dann Cookies darin und geben Sie sie dann zurück: {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. +/// tip | "Tipp" - Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. +Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. - Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. +Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + +Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +/// ### Mehr Informationen -!!! note "Technische Details" - Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. - Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. +/// Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren Dokumentation in Starlette an. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 13bca7825..377490b56 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. -!!! tip "Tipp" - `JSONResponse` selbst ist eine Unterklasse von `Response`. +/// tip | "Tipp" + +`JSONResponse` selbst ist eine Unterklasse von `Response`. + +/// Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. @@ -35,10 +38,13 @@ In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ## Eine benutzerdefinierte `Response` zurückgeben diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md index 6f4760e7f..51a364f56 100644 --- a/docs/de/docs/advanced/response-headers.md +++ b/docs/de/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response- {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. - Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +/// ## Benutzerdefinierte Header diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md index 9f9c0cf7d..3e7aeb8a0 100644 --- a/docs/de/docs/advanced/security/http-basic-auth.md +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser di * Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück: * Es enthält den gesendeten `username` und das gesendete `password`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen: @@ -59,26 +68,35 @@ Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// Dies wäre das gleiche wie: @@ -142,23 +160,32 @@ So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, v Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md index a3c975bed..380e48bbf 100644 --- a/docs/de/docs/advanced/security/index.md +++ b/docs/de/docs/advanced/security/index.md @@ -4,10 +4,13 @@ Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | "Tipp" - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index ffd34d65f..f02707698 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter an In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. -!!! warning "Achtung" - Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. +/// warning | "Achtung" - Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. +Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. - Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. +Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. - Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. +Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. - In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. +Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. - Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. +In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + +Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +/// ## OAuth2-Scopes und OpenAPI @@ -43,63 +46,87 @@ Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu dekla * `instagram_basic` wird von Facebook / Instagram verwendet. * `https://www.googleapis.com/auth/drive` wird von Google verwendet. -!!! info - In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. +/// info + +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. - Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. +Diese Details sind implementierungsspezifisch. - Diese Details sind implementierungsspezifisch. +Für OAuth2 sind es einfach nur Strings. - Für OAuth2 sind es einfach nur Strings. +/// ## Gesamtübersicht Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+" +/// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +/// -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +/// + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -109,51 +136,71 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="61-64" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="61-64" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -171,55 +218,79 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Und wir geben die Scopes als Teil des JWT-Tokens zurück. -!!! danger "Gefahr" - Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. +/// danger | "Gefahr" + +Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. - Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. +Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. -=== "Python 3.10+" +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.9+" +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.9+ - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ - ```Python hl_lines="154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +```Python hl_lines="154" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -237,62 +308,89 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). -!!! note "Hinweis" - Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. +/// note | "Hinweis" + +Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + +Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="4 139 170" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 139 170" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 140 171" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+" +/// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="3 138 167" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="4 140 171" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="3 138 167" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// -!!! info "Technische Details" - `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. +/// info | "Technische Details" - Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. +`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. - Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. +Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + +Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +/// ## `SecurityScopes` verwenden @@ -308,50 +406,71 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 106" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="7 104" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8 106" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="7 104" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// ## Die `scopes` verwenden @@ -365,50 +484,71 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="104 106-114" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="104 106-114" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Den `username` und das Format der Daten überprüfen @@ -424,50 +564,71 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="45 115-126" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="45 115-126" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Die `scopes` verifizieren @@ -475,50 +636,71 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="127-133" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="127-133" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Abhängigkeitsbaum und Scopes @@ -545,10 +727,13 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus: * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. -!!! tip "Tipp" - Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. +/// tip | "Tipp" + +Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. - Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. +Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +/// ## Weitere Details zu `SecurityScopes`. @@ -586,10 +771,13 @@ Am häufigsten ist der „Implicit“-Flow. Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. -!!! note "Hinweis" - Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. +/// note | "Hinweis" + +Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + +Aber am Ende implementieren sie denselben OAuth2-Standard. - Aber am Ende implementieren sie denselben OAuth2-Standard. +/// **FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index fe01d8e1f..3cd4c6c7d 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -8,44 +8,51 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell ## Umgebungsvariablen -!!! tip "Tipp" - Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. +/// tip | "Tipp" + +Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +/// Eine Umgebungsvariable (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels - $ export MY_NAME="Wade Wilson" +```console +// Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels +$ export MY_NAME="Wade Wilson" - // Dann könnten Sie diese mit anderen Programmen verwenden, etwa - $ echo "Hello $MY_NAME" +// Dann könnten Sie diese mit anderen Programmen verwenden, etwa +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// Erstelle eine Umgebungsvariable MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Erstelle eine Umgebungsvariable MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Verwende sie mit anderen Programmen, etwa +$ echo "Hello $Env:MY_NAME" - // Verwende sie mit anderen Programmen, etwa - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### Umgebungsvariablen mit Python auslesen @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip "Tipp" - Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. +/// tip | "Tipp" + +Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. - Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. +Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +/// Dann könnten Sie dieses Python-Programm aufrufen: @@ -114,8 +124,11 @@ Hello World from Python -!!! tip "Tipp" - Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. +/// tip | "Tipp" + +Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. + +/// ### Typen und Validierung @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" -!!! info - In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. +/// info + +In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +/// ### Das `Settings`-Objekt erstellen @@ -162,23 +178,33 @@ Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! info - In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. +/// tip | "Tipp" - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. -!!! tip "Tipp" - Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. +/// Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -!!! tip "Tipp" - Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. +/// tip | "Tipp" + +Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +/// Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. @@ -231,8 +260,11 @@ Und dann verwenden Sie diese in einer Datei `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip "Tipp" - Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. +/// tip | "Tipp" + +Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +/// ## Einstellungen in einer Abhängigkeit @@ -254,54 +286,75 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Wir werden das `@lru_cache` in Kürze besprechen. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// tip | "Tipp" + +Wir werden das `@lru_cache` in Kürze besprechen. + +Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +/// Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Einstellungen und Tests @@ -321,15 +374,21 @@ Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielle Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. -!!! tip "Tipp" - Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. +/// tip | "Tipp" + +Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. - Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. +Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. + +/// Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. -!!! tip "Tipp" - Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. +/// tip | "Tipp" + +Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +/// ### Die `.env`-Datei @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" Und dann aktualisieren Sie Ihre `config.py` mit: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! tip "Tipp" - Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. +/// tip | "Tipp" -=== "Pydantic v1" +Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! tip "Tipp" - Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. +//// -!!! info - In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip | "Tipp" + +Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. + +/// + +//// + +/// info + +In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +/// Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. @@ -390,26 +462,35 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 17d821e61..abc7624f1 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -31,18 +31,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note "Hinweis" - Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. +/// note | "Hinweis" - Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. +Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. -!!! tip "Tipp" - Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. +Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. -!!! note "Technische Details" - Sie können auch `from starlette.templating import Jinja2Templates` verwenden. +/// - **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. +/// tip | "Tipp" + +Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +/// + +/// note | "Technische Details" + +Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + +**FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +/// ## Templates erstellen diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index e7841b5f5..f131d27cd 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip "Tipp" - Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. +/// tip | "Tipp" - Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. +Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. - FastAPI kann sie in jedem Fall überschreiben. +Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + +FastAPI kann sie in jedem Fall überschreiben. + +/// Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: @@ -77,5 +96,8 @@ Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), inde app.dependency_overrides = {} ``` -!!! tip "Tipp" - Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. +/// tip | "Tipp" + +Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. + +/// diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 53de72f15..4cbc45c17 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung z {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "Hinweis" - Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. +/// note | "Hinweis" + +Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. + +/// diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index f40f5d4be..1d575a7cb 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ Dazu müssen Sie direkt auf den Request zugreifen. Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. +/// tip | "Tipp" - Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. +Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. - Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. +Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + +Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +/// ## `Request`-Dokumentation Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. -!!! note "Technische Details" - Sie können auch `from starlette.requests import Request` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.requests import Request` verwenden. + +**FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. - **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. +/// diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index e5e6a9d01..6d772b6c9 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -50,10 +50,13 @@ Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.websockets import WebSocket` verwenden. +/// note | "Technische Details" - **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. +Sie können auch `from starlette.websockets import WebSocket` verwenden. + +**FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +/// ## Nachrichten erwarten und Nachrichten senden @@ -112,46 +115,65 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. +Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. - Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. +Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. + +/// ### WebSockets mit Abhängigkeiten ausprobieren @@ -174,8 +196,11 @@ Dort können Sie einstellen: * Die „Item ID“, die im Pfad verwendet wird. * Das „Token“, das als Query-Parameter verwendet wird. -!!! tip "Tipp" - Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. +/// tip | "Tipp" + +Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +/// Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: @@ -185,17 +210,21 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// Zum Ausprobieren: @@ -209,12 +238,15 @@ Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients e Client #1596980209979 left the chat ``` -!!! tip "Tipp" - Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. +/// tip | "Tipp" + +Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + +Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. - Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. +Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. - Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. +/// ## Mehr Informationen diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index ea624ff3a..286ef1723 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -30,12 +30,17 @@ Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbri Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. -!!! note "Hinweis" - Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. +/// note | "Hinweis" +Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. -!!! check "Inspirierte **FastAPI**" - Eine automatische API-Dokumentationsoberfläche zu haben. +/// + +/// check | "Inspirierte **FastAPI**" + +Eine automatische API-Dokumentationsoberfläche zu haben. + +/// ### Flask @@ -51,11 +56,13 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -!!! check "Inspirierte **FastAPI**" - Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +/// check | "Inspirierte **FastAPI**" - Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. +Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -!!! check "Inspirierte **FastAPI**" - * Über eine einfache und intuitive API zu verfügen. - * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. - * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// check | "Inspirierte **FastAPI**" + +* Über eine einfache und intuitive API zu verfügen. +* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. +* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -!!! check "Inspirierte **FastAPI**" - Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. +/// check | "Inspirierte **FastAPI**" + +Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. - Und Standard-basierte Tools für die Oberfläche zu integrieren: +Und Standard-basierte Tools für die Oberfläche zu integrieren: - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). +Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +/// ### Flask REST Frameworks @@ -135,8 +147,11 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -!!! check "Inspirierte **FastAPI**" - Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. +/// check | "Inspirierte **FastAPI**" + +Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +/// ### Webargs @@ -148,11 +163,17 @@ Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. -!!! info - Webargs wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | "Inspirierte **FastAPI**" -!!! check "Inspirierte **FastAPI**" - Eingehende Requestdaten automatisch zu validieren. +Eingehende Requestdaten automatisch zu validieren. + +/// ### APISpec @@ -172,12 +193,17 @@ Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python- Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. -!!! info - APISpec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// +/// check | "Inspirierte **FastAPI**" -!!! check "Inspirierte **FastAPI**" - Den offenen Standard für APIs, OpenAPI, zu unterstützen. +Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Di Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// -!!! check "Inspirierte **FastAPI**" - Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. +/// check | "Inspirierte **FastAPI**" + +Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +/// ### NestJS (und Angular) @@ -219,24 +251,33 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. -!!! check "Inspirierte **FastAPI**" - Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. +/// check | "Inspirierte **FastAPI**" + +Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. - Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. +Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +/// ### Sanic Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. -!!! note "Technische Details" - Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. +/// note | "Technische Details" + +Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. - Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. +Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. -!!! check "Inspirierte **FastAPI**" - Einen Weg zu finden, eine hervorragende Performanz zu haben. +/// - Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). +/// check | "Inspirierte **FastAPI**" + +Einen Weg zu finden, eine hervorragende Performanz zu haben. + +Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +/// ### Falcon @@ -246,12 +287,15 @@ Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter e Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. -!!! check "Inspirierte **FastAPI**" - Wege zu finden, eine großartige Performanz zu erzielen. +/// check | "Inspirierte **FastAPI**" - Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. +Wege zu finden, eine großartige Performanz zu erzielen. - Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. +Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + +Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +/// ### Molten @@ -269,10 +313,13 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -!!! check "Inspirierte **FastAPI**" - Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. +/// check | "Inspirierte **FastAPI**" + +Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. - Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). +Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). + +/// ### Hug @@ -288,15 +335,21 @@ Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Fram Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. -!!! info - Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. +/// info + +Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +/// -!!! check "Ideen, die **FastAPI** inspiriert haben" - Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. +/// check | "Ideen, die **FastAPI** inspiriert haben" - Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. +Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. - Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. +Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + +Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +/// ### APIStar (≦ 0.5) @@ -322,23 +375,29 @@ Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler a Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. -!!! info - APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: +/// info + +APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: - * Django REST Framework - * Starlette (auf welchem **FastAPI** basiert) - * Uvicorn (verwendet von Starlette und **FastAPI**) +* Django REST Framework +* Starlette (auf welchem **FastAPI** basiert) +* Uvicorn (verwendet von Starlette und **FastAPI**) -!!! check "Inspirierte **FastAPI**" - Zu existieren. +/// - Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. +/// check | "Inspirierte **FastAPI**" - Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. +Zu existieren. - Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. +Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. - Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. +Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + +Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + +Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +/// ## Verwendet von **FastAPI** @@ -350,10 +409,13 @@ Das macht es äußerst intuitiv. Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. -!!! check "**FastAPI** verwendet es, um" - Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. +/// check | "**FastAPI** verwendet es, um" - **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. +Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + +**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +/// ### Starlette @@ -382,17 +444,23 @@ Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokume Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. -!!! note "Technische Details" - ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. +/// note | "Technische Details" + +ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. - Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. +Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. -!!! check "**FastAPI** verwendet es, um" - Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. +/// - Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. +/// check | "**FastAPI** verwendet es, um" - Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. +Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + +Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + +Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +/// ### Uvicorn @@ -402,12 +470,15 @@ Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielswei Es ist der empfohlene Server für Starlette und **FastAPI**. -!!! check "**FastAPI** empfiehlt es als" - Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. +/// check | "**FastAPI** empfiehlt es als" + +Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + +Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. - Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. +Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. - Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks und Geschwindigkeit diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md index c2a43ac66..74b6b6968 100644 --- a/docs/de/docs/async.md +++ b/docs/de/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. +/// note + +Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +/// --- @@ -136,8 +139,11 @@ Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ -!!! info - Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ Sie essen sie und sind fertig. ⏹ Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 -!!! info - Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// --- @@ -392,12 +401,15 @@ All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindrucken ## Sehr technische Details -!!! warning "Achtung" - Das folgende können Sie wahrscheinlich überspringen. +/// warning | "Achtung" + +Das folgende können Sie wahrscheinlich überspringen. + +Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. - Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. +Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. - Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. +/// ### Pfadoperation-Funktionen diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md index b1bd62496..58567ad7f 100644 --- a/docs/de/docs/contributing.md +++ b/docs/de/docs/contributing.md @@ -24,63 +24,73 @@ Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie könn Aktivieren Sie die neue Umgebung mit: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// + +//// tab | Windows Bash - Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): +Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// Um zu überprüfen, ob es funktioniert hat, geben Sie ein: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` -
+
+ +//// Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip "Tipp" - Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. +/// tip | "Tipp" + +Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. - Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. +Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. + +/// ### Benötigtes mit pip installieren @@ -125,10 +138,13 @@ Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python- Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. -!!! note "Technische Details" - Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. +/// note | "Technische Details" + +Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. - Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. +Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. + +/// ### Den Code formatieren @@ -170,20 +186,23 @@ Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | "Tipp" - Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - ```console - $ cd docs/en/ - ``` +Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: - Führen Sie dann `mkdocs` in diesem Verzeichnis aus: +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Führen Sie dann `mkdocs` in diesem Verzeichnis aus: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer-CLI (optional) @@ -210,8 +229,11 @@ Die Dokumentation verwendet Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. +/// tip | "Tipp" + +Sie können Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. + +Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. - Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. +/// * Überprüfen Sie, ob es eine GitHub-Diskussion gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. @@ -278,8 +303,11 @@ Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. -!!! tip "Tipp" - Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. +/// tip | "Tipp" + +Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. + +/// Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus: @@ -296,20 +324,23 @@ $ python ./scripts/docs.py live es -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | "Tipp" + +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: +Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +Dann führen Sie in dem Verzeichnis `mkdocs` aus: - Dann führen Sie in dem Verzeichnis `mkdocs` aus: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// Jetzt können Sie auf http://127.0.0.1:8008 gehen und Ihre Änderungen live sehen. @@ -329,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Tipp" - Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. +/// tip | "Tipp" + +Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. + +/// Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉 @@ -365,8 +399,11 @@ Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfigurat INHERIT: ../en/mkdocs.yml ``` -!!! tip "Tipp" - Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. +/// tip | "Tipp" + +Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. + +/// Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen. diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 5e1a4f109..3c1c0cfce 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -151,10 +151,13 @@ Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, we Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... -!!! tip "Tipp" - ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. +/// tip | "Tipp" - Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. +... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + +Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +/// Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. @@ -238,10 +241,13 @@ Hier sind einige mögliche Kombinationen und Strategien: * **Cloud-Dienste**, welche das für Sie erledigen * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. -!!! tip "Tipp" - Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. +/// tip | "Tipp" + +Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + +Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. - Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// ## Schritte vor dem Start @@ -257,10 +263,13 @@ Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. -!!! tip "Tipp" - Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. +/// tip | "Tipp" - In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 +Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + +In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +/// ### Beispiele für Strategien für Vorab-Schritte @@ -272,8 +281,11 @@ Hier sind einige mögliche Ideen: * Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. -!!! tip "Tipp" - Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// tip | "Tipp" + +Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +/// ## Ressourcennutzung diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index b86cf92a4..2186d16c5 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -4,8 +4,11 @@ Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. -!!! tip "Tipp" - Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). +/// tip | "Tipp" + +Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +///
Dockerfile-Vorschau 👀 @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. +/// info + +Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. - Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 +Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +/// ### Den **FastAPI**-Code erstellen @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. -!!! tip "Tipp" - Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 +/// tip | "Tipp" + +Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +/// Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: @@ -293,10 +302,13 @@ $ docker build -t myimage . -!!! tip "Tipp" - Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. +/// tip | "Tipp" + +Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. + +In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). - In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). +/// ### Den Docker-Container starten @@ -394,8 +406,11 @@ Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und sp Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. -!!! tip "Tipp" - Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. +/// tip | "Tipp" + +Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +/// Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). @@ -423,8 +438,11 @@ Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, * Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. -!!! tip "Tipp" - Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. +/// tip | "Tipp" + +Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +/// Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. @@ -503,8 +521,11 @@ Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächl Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. -!!! info - Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. +/// info + +Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. + +/// Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. @@ -520,8 +541,11 @@ Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [C * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "Achtung" - Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). +/// warning | "Achtung" + +Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +/// Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. @@ -529,8 +553,11 @@ Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotz Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. -!!! tip "Tipp" - Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | "Tipp" + +Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Anzahl der Prozesse auf dem offiziellen Docker-Image @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. -!!! tip "Tipp" - Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. +/// tip | "Tipp" + +Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +/// Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index 3ebe59af2..b1f0aca77 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -4,8 +4,11 @@ Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ Aber es ist viel komplexer als das. -!!! tip "Tipp" - Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. +/// tip | "Tipp" + +Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +/// Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich https://howhttps.works/ an. @@ -68,8 +71,11 @@ In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. -!!! tip "Tipp" - Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. +/// tip | "Tipp" + +Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +/// ### DNS @@ -115,8 +121,11 @@ Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verb Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. -!!! tip "Tipp" - Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. +/// tip | "Tipp" + +Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +/// ### HTTPS-Request diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index ddc31dc5b..2b4ed3fad 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -22,75 +22,89 @@ Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als ** Sie können einen ASGI-kompatiblen Server installieren mit: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. +* Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip | "Tipp" -
+Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. - !!! tip "Tipp" - Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. +Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. - Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. +/// -=== "Hypercorn" +//// - * Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. +//// tab | Hypercorn -
+* Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+... oder jeden anderen ASGI-Server. - ... oder jeden anderen ASGI-Server. +//// ## Das Serverprogramm ausführen Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning | "Achtung" -
+Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. -!!! warning "Achtung" - Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. +Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. - Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. +Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. - Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. +/// ## Hypercorn mit Trio diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md index 04d48dc6c..5cd282b4b 100644 --- a/docs/de/docs/deployment/server-workers.md +++ b/docs/de/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal Hier zeige ich Ihnen, wie Sie **Gunicorn** mit **Uvicorn Workerprozessen** verwenden. -!!! info - Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// info - Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. +Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +/// ## Gunicorn mit Uvicorn-Workern diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md index d71aded22..2d10ac4b6 100644 --- a/docs/de/docs/deployment/versions.md +++ b/docs/de/docs/deployment/versions.md @@ -42,8 +42,11 @@ Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unt FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. -!!! tip "Tipp" - Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. +/// tip | "Tipp" + +Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +/// Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. -!!! tip "Tipp" - „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. +/// tip | "Tipp" + +„MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +/// ## Upgrade der FastAPI-Versionen diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md index 1dfa70767..ae5a6c908 100644 --- a/docs/de/docs/external-links.md +++ b/docs/de/docs/external-links.md @@ -6,11 +6,17 @@ Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. Hier ist eine unvollständige Liste einiger davon. -!!! tip "Tipp" - Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen Pull Request und fügen Sie es hinzu. +/// tip | "Tipp" -!!! note "Hinweis Deutsche Übersetzung" - Die folgenden Überschriften und Links werden aus einer anderen Datei gelesen und sind daher nicht ins Deutsche übersetzt. +Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen Pull Request und fügen Sie es hinzu. + +/// + +/// note | "Hinweis Deutsche Übersetzung" + +Die folgenden Überschriften und Links werden aus einer anderen Datei gelesen und sind daher nicht ins Deutsche übersetzt. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 1e68aff88..b268604fa 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` bedeutet: +/// info - Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. +`**second_user_data` bedeutet: + +Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. + +/// ### Editor Unterstützung diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index d7d7b3359..2c84a5e5b 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -169,12 +169,15 @@ Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich dir * Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. -!!! info - Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. +/// info - Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 +Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. - Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 +Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + +Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +/// * Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. @@ -225,10 +228,13 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. -!!! tip "Tipp" - Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. +/// tip | "Tipp" + +Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + +Nutzen Sie den Chat nur für andere allgemeine Gespräche. - Nutzen Sie den Chat nur für andere allgemeine Gespräche. +/// ### Den Chat nicht für Fragen verwenden diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index a9271b3f3..e8750f7c2 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -40,12 +40,15 @@ Und genau so für ReDoc ... {!../../../docs_src/custom_docs_ui/tutorial001.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | "Tipp" - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +/// ### Eine *Pfadoperation* erstellen, um es zu testen @@ -177,12 +180,15 @@ Und genau so für ReDoc ... {!../../../docs_src/custom_docs_ui/tutorial002.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | "Tipp" + +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +/// ### Eine *Pfadoperation* erstellen, um statische Dateien zu testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index b51a20bfc..a0c4a0e0c 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. -!!! danger "Gefahr" - Dies ist eine „fortgeschrittene“ Funktion. +/// danger | "Gefahr" - Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. +Dies ist eine „fortgeschrittene“ Funktion. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +/// ## Anwendungsfälle @@ -27,8 +30,11 @@ Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Reques ### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen -!!! tip "Tipp" - Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. +/// tip | "Tipp" + +Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +/// Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. @@ -54,16 +60,19 @@ Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` z {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "Technische Details" - Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. +/// note | "Technische Details" - Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. +Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. - Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. +Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. - Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. +Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. - Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. +Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + +Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. + +/// Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. @@ -75,10 +84,13 @@ Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch b ## Zugriff auf den Requestbody in einem Exceptionhandler -!!! tip "Tipp" - Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). +/// tip | "Tipp" + +Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + +Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. - Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. +/// Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 2fbfa13e5..347c5bed3 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ Und diese Funktion `get_openapi()` erhält als Parameter: * `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. * `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. -!!! info - Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. +/// info + +Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +/// ## Überschreiben der Standardeinstellungen diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index b8e0bdddd..19af25bb3 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -4,12 +4,15 @@ Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **Gr Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. -!!! tip "Tipp" - **GraphQL** löst einige sehr spezifische Anwendungsfälle. +/// tip | "Tipp" - Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. +**GraphQL** löst einige sehr spezifische Anwendungsfälle. - Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 +Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. + +Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 + +/// ## GraphQL-Bibliotheken @@ -46,8 +49,11 @@ Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integra Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. -!!! tip "Tipp" - Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. +/// tip | "Tipp" + +Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +/// ## Mehr darüber lernen diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md index 101829ff8..75779a01c 100644 --- a/docs/de/docs/how-to/index.md +++ b/docs/de/docs/how-to/index.md @@ -6,5 +6,8 @@ Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meis Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. -!!! tip "Tipp" - Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. +/// tip | "Tipp" + +Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 000bcf633..eaecb27de 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,123 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +```Python hl_lines="7" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` -
- 👀 Vollständige Dateivorschau +
+👀 Vollständige Dateivorschau - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` -
+
-=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +//// tab | Python 3.9+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} -
- 👀 Vollständige Dateivorschau +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +
+👀 Vollständige Dateivorschau -
+```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +
- ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +//// - # Code unterhalb weggelassen 👇 - ``` +//// tab | Python 3.8+ -
- 👀 Vollständige Dateivorschau +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +# Code unterhalb weggelassen 👇 +``` -
+
+👀 Vollständige Dateivorschau + +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +# Code unterhalb weggelassen 👇 +``` - # Code unterhalb weggelassen 👇 - ``` +
+👀 Vollständige Dateivorschau -
- 👀 Vollständige Dateivorschau +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +
-
+//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` -
- 👀 Vollständige Dateivorschau +
+👀 Vollständige Dateivorschau - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -
+
-=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +//// tab | Python 3.8+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} -
- 👀 Vollständige Dateivorschau +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +
+👀 Vollständige Dateivorschau -
+```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -130,23 +142,29 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -199,26 +217,35 @@ Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. -!!! info - Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 +/// info + +Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +//// ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index d11a193dd..9bbff83d3 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -12,8 +12,11 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. -!!! note "Hinweis" - Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. +/// note | "Hinweis" + +Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// ## Motivation @@ -170,45 +173,55 @@ Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die B Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll. -=== "Python 3.9+" +//// tab | Python 3.9+ - Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). - Als Typ nehmen Sie `list`. +Als Typ nehmen Sie `list`. - Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): - Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). - Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. +Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. - Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! tip "Tipp" - Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. +/// tip | "Tipp" - In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). +Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. + +In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). + +/// Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. -!!! tip "Tipp" - Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. +/// tip | "Tipp" + +Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. + +/// Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen: @@ -224,17 +237,21 @@ Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet ent Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// Das bedeutet: @@ -249,17 +266,21 @@ Der erste Typ-Parameter ist für die Schlüssel des `dict`. Der zweite Typ-Parameter ist für die Werte des `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Das bedeutet: @@ -275,17 +296,21 @@ In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann. @@ -305,23 +330,29 @@ Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "Python 3.8+ Alternative" +//// tab | Python 3.8+ Alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### `Union` oder `Optional` verwenden? @@ -366,47 +397,53 @@ Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmer Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt. -=== "Python 3.10+" +//// tab | Python 3.10+ + +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + +* `list` +* `tuple` +* `set` +* `dict` - Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (so wie unter Python 3.8) +* ... und andere. - Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: +In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. - * `Union` - * `Optional` (so wie unter Python 3.8) - * ... und andere. +//// - In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. +//// tab | Python 3.9+ -=== "Python 3.9+" +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): - Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: - Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: +* `Union` +* `Optional` +* ... und andere. - * `Union` - * `Optional` - * ... und andere. +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ... und andere. +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ... und andere. + +//// ### Klassen als Typen @@ -446,55 +483,71 @@ Und Sie erhalten volle Editor-Unterstützung für dieses Objekt. Ein Beispiel aus der offiziellen Pydantic Dokumentation: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// tab | Python 3.8+ -!!! info - Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an. +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an. + +/// **FastAPI** basiert vollständig auf Pydantic. Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen. -!!! tip "Tipp" - Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren. +/// tip | "Tipp" + +Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren. + +/// ## Typhinweise mit Metadaten-Annotationen Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. - In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. +Es wird bereits mit **FastAPI** installiert sein. - Es wird bereits mit **FastAPI** installiert sein. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`. @@ -506,10 +559,13 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa Später werden Sie sehen, wie **mächtig** es sein kann. -!!! tip "Tipp" - Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ +/// tip | "Tipp" - Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 +Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ + +Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 + +/// ## Typhinweise in **FastAPI** @@ -533,5 +589,8 @@ Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt. -!!! info - Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`. +/// info + +Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`. + +/// diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md index e9362b962..6fd0ef15f 100644 --- a/docs/de/docs/reference/index.md +++ b/docs/de/docs/reference/index.md @@ -4,5 +4,8 @@ Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribu Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen. -!!! note "Hinweis Deutsche Übersetzung" - Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. +/// note | "Hinweis Deutsche Übersetzung" + +Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. + +/// diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md index b170c1e40..cf7eb61ad 100644 --- a/docs/de/docs/reference/request.md +++ b/docs/de/docs/reference/request.md @@ -8,7 +8,10 @@ Sie können es direkt von `fastapi` importieren: from fastapi import Request ``` -!!! tip "Tipp" - Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. +/// tip | "Tipp" + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +/// ::: fastapi.Request diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md index 35657172c..d5597d0ee 100644 --- a/docs/de/docs/reference/websockets.md +++ b/docs/de/docs/reference/websockets.md @@ -6,8 +6,11 @@ Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter from fastapi import WebSocket ``` -!!! tip "Tipp" - Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. +/// tip | "Tipp" + +Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. + +/// ::: fastapi.WebSocket options: diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index a7bfd55a7..0852288d5 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md index 66dee0a9a..986a99a38 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, das **FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität. -!!! info - Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. +/// info + +Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. + +/// ## Eine Beispiel-Dateistruktur @@ -26,16 +29,19 @@ Nehmen wir an, Sie haben eine Dateistruktur wie diese: │   └── admin.py ``` -!!! tip "Tipp" - Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. +/// tip | "Tipp" + +Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. - Das ermöglicht den Import von Code aus einer Datei in eine andere. +Das ermöglicht den Import von Code aus einer Datei in eine andere. - In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: +In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`. * Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`. @@ -99,8 +105,11 @@ Alle die gleichen Optionen werden unterstützt. Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. -!!! tip "Tipp" - In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. +/// tip | "Tipp" + +In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. + +/// Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`. @@ -112,31 +121,43 @@ Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`) Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` - ```Python hl_lines="3 6-8" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 5-7" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} - ``` +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="1 4-6" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app/dependencies.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | "Tipp" + +Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. + +Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. + +/// ## Ein weiteres Modul mit `APIRouter`. @@ -180,8 +201,11 @@ Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen, Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden. -!!! tip "Tipp" - Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. +/// tip | "Tipp" + +Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. + +/// Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: @@ -198,11 +222,17 @@ Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: * Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten. * Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen. -!!! tip "Tipp" - `dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. +/// tip | "Tipp" + +`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. + +/// + +/// check -!!! check - Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. +Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. + +/// ### Die Abhängigkeiten importieren @@ -218,8 +248,11 @@ Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: #### Wie relative Importe funktionieren -!!! tip "Tipp" - Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. +/// tip | "Tipp" + +Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. + +/// Ein einzelner Punkt `.`, wie in: @@ -286,10 +319,13 @@ Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *P {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip "Tipp" - Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. +/// tip | "Tipp" - Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. +Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. + +Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. + +/// ## Das Haupt-`FastAPI`. @@ -345,20 +381,23 @@ Wir könnten sie auch wie folgt importieren: from app.routers import items, users ``` -!!! info - Die erste Version ist ein „relativer Import“: +/// info - ```Python - from .routers import items, users - ``` +Die erste Version ist ein „relativer Import“: - Die zweite Version ist ein „absoluter Import“: +```Python +from .routers import items, users +``` + +Die zweite Version ist ein „absoluter Import“: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module. - Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module. +/// ### Namenskollisionen vermeiden @@ -390,26 +429,35 @@ Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. +/// info + +`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. - Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. +Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. + +/// Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen. Es wird alle Routen von diesem Router als Teil von dieser inkludieren. -!!! note "Technische Details" - Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. +/// note | "Technische Details" + +Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. + +Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. - Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. +/// -!!! check - Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. +/// check - Dies dauert Mikrosekunden und geschieht nur beim Start. +Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. - Es hat also keinen Einfluss auf die Leistung. ⚡ +Dies dauert Mikrosekunden und geschieht nur beim Start. + +Es hat also keinen Einfluss auf die Leistung. ⚡ + +/// ### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen @@ -456,16 +504,19 @@ Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. -!!! info "Sehr technische Details" - **Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. +/// info | "Sehr technische Details" + +**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. + +--- - --- +Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. - Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. +Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. - Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. +Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. - Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. +/// ## Es in der automatischen API-Dokumentation ansehen diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index 643be7489..33f7713ee 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati Importieren Sie es zuerst: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! warning "Achtung" - Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "Achtung" + +Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) + +/// ## Modellattribute deklarieren Dann können Sie `Field` mit Modellattributen deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. -!!! note "Technische Details" - Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. +/// note | "Technische Details" - Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. +Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. - `Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. +Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. - Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. +`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. -!!! tip "Tipp" - Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. +Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. + +/// + +/// tip | "Tipp" + +Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. + +/// ## Zusätzliche Information hinzufügen @@ -105,8 +146,11 @@ Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarier Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren. -!!! warning "Achtung" - Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. +/// warning | "Achtung" + +Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. + +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 6a237243e..977e17671 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarati Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip | "Tipp" -!!! note "Hinweis" - Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note | "Hinweis" + +Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. + +/// ## Mehrere Body-Parameter @@ -62,17 +81,21 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). @@ -93,8 +116,11 @@ Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden, } ``` -!!! note "Hinweis" - Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. +/// note | "Hinweis" + +Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. + +/// **FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`. @@ -110,41 +136,57 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// In diesem Fall erwartet **FastAPI** einen Body wie: @@ -184,44 +226,63 @@ q: str | None = None Zum Beispiel: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +//// -!!! info - `Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. +/// info + +`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. + +/// ## Einen einzelnen Body-Parameter einbetten @@ -237,41 +298,57 @@ item: Item = Body(embed=True) so wie in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// In diesem Fall erwartet **FastAPI** einen Body wie: diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index a7a15a6c2..8aef965f4 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. @@ -61,23 +65,29 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set-Typen @@ -87,23 +97,29 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. @@ -125,45 +141,57 @@ Alles das beliebig tief verschachtelt. Wir können zum Beispiel ein `Image`-Modell definieren. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Das Kindmodell als Typ verwenden Und dann können wir es als Typ eines Attributes verwenden. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: @@ -196,23 +224,29 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. @@ -220,23 +254,29 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: @@ -264,33 +304,45 @@ Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie } ``` -!!! info - Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. +/// info + +Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. + +/// ## Tief verschachtelte Modelle Sie können beliebig tief verschachtelte Modelle definieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. -!!! info - Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. +/// ## Bodys aus reinen Listen @@ -308,17 +360,21 @@ images: list[Image] so wie in: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Editor-Unterstützung überall @@ -348,26 +404,33 @@ Das schauen wir uns mal an. Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. -!!! tip "Tipp" - Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. +Aber Pydantic hat automatische Datenkonvertierung. - Aber Pydantic hat automatische Datenkonvertierung. +Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. - Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. +Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. - Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index 2b3716d6f..b83554914 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ Um einen Artikel zu aktualisieren, können Sie die ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// `PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. @@ -48,14 +54,17 @@ Sie können auch die ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Pydantics `update`-Parameter verwenden Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben. -!!! info - In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. +/// info + +In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. - Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. +Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// Wie in `stored_item_model.model_copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Rekapitulation zum teilweisen Ersetzen @@ -134,32 +161,44 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: * Speichern Sie die Daten in Ihrer Datenbank. * Geben Sie das aktualisierte Modell zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. -=== "Python 3.8+" +Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip "Tipp" - Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. +/// note | "Hinweis" - Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. +Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. -!!! note "Hinweis" - Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. +Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). - Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). +Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. - Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. +/// diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 6611cb51a..3fdd4ade3 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -8,28 +8,35 @@ Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unb Um einen **Request**body zu deklarieren, verwenden Sie Pydantic-Modelle mit allen deren Fähigkeiten und Vorzügen. -!!! info - Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. +/// info - Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. +Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. - Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. +Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. + +Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. + +/// ## Importieren Sie Pydantics `BaseModel` Zuerst müssen Sie `BaseModel` von `pydantic` importieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## Erstellen Sie Ihr Datenmodell @@ -37,17 +44,21 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. Verwenden Sie Standard-Python-Typen für die Klassenattribute: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. @@ -75,17 +86,21 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. @@ -134,32 +149,39 @@ Aber Sie bekommen die gleiche Editor-Unterstützung in -!!! tip "Tipp" - Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. +/// tip | "Tipp" + +Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. - Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: +Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: - * Code-Vervollständigung - * Typüberprüfungen - * Refaktorisierung - * Suchen - * Inspektionen +* Code-Vervollständigung +* Typüberprüfungen +* Refaktorisierung +* Suchen +* Inspektionen + +/// ## Das Modell verwenden Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## Requestbody- + Pfad-Parameter @@ -167,17 +189,21 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. **FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## Requestbody- + Pfad- + Query-Parameter @@ -185,17 +211,21 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** **FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// Die Funktionsparameter werden wie folgt erkannt: @@ -203,10 +233,13 @@ Die Funktionsparameter werden wie folgt erkannt: * Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. * Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. -!!! note "Hinweis" - FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` +/// note | "Hinweis" + +FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` + +Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. - Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. +/// ## Ohne Pydantic diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index c95e28c7d..0060db8e8 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Deklarieren der Abhängigkeit im „Dependant“ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. @@ -179,8 +230,11 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. -!!! tip "Tipp" - Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. +/// tip | "Tipp" + +Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. + +/// Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum: @@ -201,10 +255,13 @@ common_parameters --> read_users Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen. -!!! check - Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. +/// check + +Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. + +Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. - Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. +/// ## `Annotated`-Abhängigkeiten wiederverwenden @@ -218,28 +275,37 @@ commons: Annotated[dict, Depends(common_parameters)] Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. +Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. - Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 +Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 + +/// Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`. @@ -255,8 +321,11 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. -!!! note "Hinweis" - Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. +/// note | "Hinweis" + +Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. + +/// ## Integriert in OpenAPI diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 0fa2af839..12664a8cd 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ Diese können so **tief** verschachtelt sein, wie nötig. Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.10 nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. @@ -54,41 +70,57 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 nicht annotiert - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Betrachten wir die deklarierten Parameter: @@ -101,46 +133,65 @@ Betrachten wir die deklarierten Parameter: Diese Abhängigkeit verwenden wir nun wie folgt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 nicht annotiert" +//// tab | Python 3.8 nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8 nicht annotiert" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info -!!! info - Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. +Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. - Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. +Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ Und es speichert den zurückgegebenen Wert in einem ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. @@ -38,5 +42,8 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard- ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index cdf16c4ba..cfd0230eb 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -8,31 +8,41 @@ Insbesondere Benutzermodelle, denn: * Das **herausgehende Modell** sollte kein Passwort haben. * Das **Datenbankmodell** sollte wahrscheinlich ein gehashtes Passwort haben. -!!! danger "Gefahr" - Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. +/// danger | "Gefahr" - Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. +Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. + +Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. + +/// ## Mehrere Modelle Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. -!!! info - In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. - Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. +/// ### Über `**user_in.dict()` @@ -144,8 +154,11 @@ UserInDB( ) ``` -!!! warning "Achtung" - Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. +/// warning | "Achtung" + +Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. + +/// ## Verdopplung vermeiden @@ -163,17 +176,21 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union`, oder `anyOf` @@ -183,20 +200,27 @@ Das wird in OpenAPI mit `anyOf` angezeigt. Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`: -!!! note "Hinweis" - Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. +/// note | "Hinweis" -=== "Python 3.10+" +Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` in Python 3.10 @@ -218,17 +242,21 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// ## Response mit beliebigem `dict` @@ -238,17 +266,21 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index 27ba3ec16..b9e38707c 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "Hinweis" - Der Befehl `uvicorn main:app` bezieht sich auf: +/// note | "Hinweis" - * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). - * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. - * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. +Der Befehl `uvicorn main:app` bezieht sich auf: + +* `main`: die Datei `main.py` (das sogenannte Python-„Modul“). +* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. + +/// In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht: @@ -136,10 +139,13 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. -!!! note "Technische Details" - `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. +/// note | "Technische Details" + +`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. - Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. +Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. + +/// ### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. +/// info + +Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +/// Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. @@ -250,16 +259,19 @@ Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die * den Pfad `/` * unter der Verwendung der get-Operation gehen -!!! info "`@decorator` Information" - Diese `@something`-Syntax wird in Python „Dekorator“ genannt. +/// info | "`@decorator` Information" - Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). +Diese `@something`-Syntax wird in Python „Dekorator“ genannt. - Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. +Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). - In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. +Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. - Dies ist der „**Pfadoperation-Dekorator**“. +In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. + +Dies ist der „**Pfadoperation-Dekorator**“. + +/// Sie können auch die anderen Operationen verwenden: @@ -274,14 +286,17 @@ Oder die exotischeren: * `@app.patch()` * `@app.trace()` -!!! tip "Tipp" - Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. +/// tip | "Tipp" + +Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. - **FastAPI** erzwingt keine bestimmte Bedeutung. +**FastAPI** erzwingt keine bestimmte Bedeutung. - Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. +Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. - Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. +Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. + +/// ### Schritt 4: Definieren der **Pfadoperation-Funktion** @@ -309,8 +324,11 @@ Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Hinweis" - Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. +/// note | "Hinweis" + +Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +/// ### Schritt 5: den Inhalt zurückgeben diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md index af658b971..6ee47948c 100644 --- a/docs/de/docs/tutorial/handling-errors.md +++ b/docs/de/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere } ``` -!!! tip "Tipp" - Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. +/// tip | "Tipp" - Zum Beispiel ein `dict`, eine `list`, usw. +Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. - Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. +Zum Beispiel ein `dict`, eine `list`, usw. + +Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. + +/// ## Benutzerdefinierte Header hinzufügen @@ -106,10 +109,13 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Technische Details" - Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. +/// ## Die Default-Exceptionhandler überschreiben @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` vs. `ValidationError` -!!! warning "Achtung" - Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. +/// warning | "Achtung" + +Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. + +/// `RequestValidationError` ist eine Unterklasse von Pydantics `ValidationError`. @@ -183,10 +192,13 @@ Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zu {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import PlainTextResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import PlainTextResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### Den `RequestValidationError`-Body verwenden diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md index 3c9807f47..c8c3a4c57 100644 --- a/docs/de/docs/tutorial/header-params.md +++ b/docs/de/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch . +/// tip | "Tipp" + +Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist. + +/// + +/// note | "Technische Details" - Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist. +Sie könnten auch `from starlette.requests import Request` verwenden. -!!! note "Technische Details" - Sie könnten auch `from starlette.requests import Request` verwenden. +**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. - **FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. +/// ### Vor und nach der `response` diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 80a4fadc9..03980b7dd 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. -!!! warning "Achtung" - Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. +/// warning | "Achtung" + +Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. + +/// ## Response-Statuscode @@ -13,52 +16,67 @@ Sie können direkt den `int`-Code übergeben, etwa `404`. Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. -!!! note "Technische Details" - Sie können auch `from starlette import status` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. +/// ## Tags Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet: @@ -80,23 +98,29 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Beschreibung mittels Docstring @@ -104,23 +128,29 @@ Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// In der interaktiven Dokumentation sieht das dann so aus: @@ -130,31 +160,43 @@ In der interaktiven Dokumentation sieht das dann so aus: Die Response können Sie mit dem Parameter `response_description` beschreiben: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check -!!! info - beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. +OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. -!!! check - OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. +Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. - Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. +/// diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md index aa3b59b8b..3908a0b2d 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metad Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. -!!! info - FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. - Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. - Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. +/// ## Metadaten deklarieren @@ -55,53 +74,75 @@ Sie können die gleichen Parameter deklarieren wie für `Query`. Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! note "Hinweis" - Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. +/// - Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note | "Hinweis" + +Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. + +Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. + +Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. + +/// ## Sortieren Sie die Parameter, wie Sie möchten -!!! tip "Tipp" - Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. +/// tip | "Tipp" + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren. @@ -117,33 +158,45 @@ Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Nam Sie können Ihre Funktion also so deklarieren: -=== "Python 3.8 nicht annotiert" +//// tab | Python 3.8 nicht annotiert + +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Sortieren Sie die Parameter wie Sie möchten: Tricks -!!! tip "Tipp" - Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. +/// tip | "Tipp" + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen. @@ -168,43 +221,56 @@ Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Par Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Validierung von Zahlen: Größer oder gleich Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Validierung von Zahlen: Größer und kleiner oder gleich @@ -213,26 +279,35 @@ Das Gleiche trifft zu auf: * `gt`: `g`reater `t`han – größer als * `le`: `l`ess than or `e`qual – kleiner oder gleich -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Validierung von Zahlen: Floats, größer und kleiner @@ -244,26 +319,35 @@ Hier wird es wichtig, in der Lage zu sein, lt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Zusammenfassung @@ -276,18 +360,24 @@ Und Sie können auch Validierungen für Zahlen deklarieren: * `lt`: `l`ess `t`han – kleiner als * `le`: `l`ess than or `e`qual – kleiner oder gleich -!!! info - `Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. +/// info + +`Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. + +Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. + +/// + +/// note | "Technische Details" - Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. +`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. -!!! note "Technische Details" - `Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. +Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. - Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. +Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. - Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. +Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. - Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. +Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. - Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. +/// diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md index 8c8f2e008..2c1b691a8 100644 --- a/docs/de/docs/tutorial/path-params.md +++ b/docs/de/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion dekl In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl. -!!! check - Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. +/// check + +Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. + +/// ## Daten-Konversion @@ -35,10 +38,13 @@ Wenn Sie dieses Beispiel ausführen und Ihren Browser unter „parsen“. - Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch „parsen“. +/// ## Datenvalidierung @@ -65,12 +71,15 @@ Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist. Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: http://127.0.0.1:8000/items/4.2 -!!! check - Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. +/// check - Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. +Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. - Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. +Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. + +Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. + +/// ## Dokumentation @@ -78,10 +87,13 @@ Wenn Sie die Seite -!!! check - Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). +/// check + +Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). + +Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. - Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. +/// ## Nützliche Standards. Alternative Dokumentation @@ -141,11 +153,17 @@ Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaub {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4. +/// info -!!! tip "Tipp" - Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen. +Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4. + +/// + +/// tip | "Tipp" + +Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen. + +/// ### Deklarieren Sie einen *Pfad-Parameter* @@ -181,8 +199,11 @@ Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name. {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Tipp" - Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. +/// tip | "Tipp" + +Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. + +/// #### *Enum-Member* zurückgeben @@ -235,10 +256,13 @@ Sie verwenden das also wie folgt: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Tipp" - Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. +/// tip | "Tipp" + +Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. + +In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. - In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md index 92f2bbe7c..ab30fc6cf 100644 --- a/docs/de/docs/tutorial/query-params-str-validations.md +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Nehmen wir als Beispiel die folgende Anwendung: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. -!!! note "Hinweis" - FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist +/// note | "Hinweis" - `Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. +FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist + +`Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +/// ## Zusätzliche Validierung @@ -34,30 +41,37 @@ Importieren Sie zuerst: * `Query` von `fastapi` * `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ - In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. +In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// - In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. +//// tab | Python 3.8+ - Es wird bereits mit FastAPI installiert sein. +In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +Es wird bereits mit FastAPI installiert sein. -!!! info - FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. +//// - Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// ## `Annotated` im Typ des `q`-Parameters verwenden @@ -67,31 +81,39 @@ Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀 Wir hatten diese Typannotation: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// - ```Python - q: str | None = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Union[str, None] = None +``` - ```Python - q: Union[str, None] = None - ``` +//// Wir wrappen das nun in `Annotated`, sodass daraus wird: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: Annotated[str | None] = None - ``` +```Python +q: Annotated[str | None] = None +``` -=== "Python 3.8+" +//// - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`. @@ -101,17 +123,21 @@ Wenden wir uns jetzt den spannenden Dingen zu. 🎉 Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. @@ -127,22 +153,29 @@ FastAPI wird nun: Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. -!!! tip "Tipp" - Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 +/// tip | "Tipp" + +Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 + +/// So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI). @@ -172,22 +205,25 @@ q: str | None = None Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren. -!!! info - Bedenken Sie, dass: +/// info - ```Python - = None - ``` +Bedenken Sie, dass: - oder: +```Python += None +``` - ```Python - = Query(default=None) - ``` +oder: - der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. +```Python += Query(default=None) +``` + +der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. + +Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. - Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. +/// Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird: @@ -239,81 +275,113 @@ Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch Sie können auch einen Parameter `min_length` hinzufügen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// ## Reguläre Ausdrücke hinzufügen Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: @@ -331,11 +399,13 @@ Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Paramet Sie könnten immer noch Code sehen, der den alten Namen verwendet: -=== "Python 3.10+ Pydantic v1" +//// tab | Python 3.10+ Pydantic v1 + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} - ``` +//// Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓 @@ -345,29 +415,41 @@ Sie können natürlich andere Defaultwerte als `None` verwenden. Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note | "Hinweis" -!!! note "Hinweis" - Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. +Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. + +/// ## Erforderliche Parameter @@ -385,75 +467,103 @@ q: Union[str, None] = None Aber jetzt deklarieren wir den Parameter mit `Query`, wie in: -=== "Annotiert" +//// tab | Annotiert - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// -=== "Nicht annotiert" +//// tab | Nicht annotiert - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 - !!! tip "Tipp" - Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. +/// - Verwenden Sie bitte trotzdem die `Annotated`-Version. 😉 +//// ### Erforderlich mit Ellipse (`...`) Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// info -!!! info - Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse). +Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse). - Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. +Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. + +/// Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. @@ -463,47 +573,69 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +/// tip | "Tipp" -!!! tip "Tipp" - Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. +Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. -!!! tip "Tipp" - Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. +/// ## Query-Parameter-Liste / Mehrere Werte @@ -511,50 +643,71 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+" +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.9+ nicht annotiert - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +/// tip | "Tipp" -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Dann, mit einer URL wie: @@ -575,8 +728,11 @@ Die Response für diese URL wäre also: } ``` -!!! tip "Tipp" - Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. +/// tip | "Tipp" + +Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. + +/// Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte. @@ -586,35 +742,49 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` + +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +/// -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +//// Wenn Sie auf: @@ -637,31 +807,43 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +/// note | "Hinweis" -!!! note "Hinweis" - Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. +Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. - Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. +Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. + +/// ## Deklarieren von mehr Metadaten @@ -669,86 +851,121 @@ Sie können mehr Informationen zum Parameter hinzufügen. Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. -!!! note "Hinweis" - Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. +/// note | "Hinweis" + +Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. - Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. +Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. + +/// Sie können einen Titel hinzufügen – `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// Und eine Beschreibung – `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// ## Alias-Parameter @@ -768,41 +985,57 @@ Aber Sie möchten dennoch exakt `item-query` verwenden. Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// ## Parameter als deprecated ausweisen @@ -812,41 +1045,57 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// Die Dokumentation wird das so anzeigen: @@ -856,41 +1105,57 @@ Die Dokumentation wird das so anzeigen: Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index 1b9b56bea..136852216 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein: Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. -!!! check - Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. +/// check + +Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. + +/// ## Query-Parameter Typkonvertierung Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Wenn Sie nun zu: @@ -136,17 +147,21 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. Parameter werden anhand ihres Namens erkannt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Erforderliche Query-Parameter @@ -204,17 +219,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// In diesem Fall gibt es drei Query-Parameter: @@ -222,5 +241,8 @@ In diesem Fall gibt es drei Query-Parameter: * `skip`, ein `int` mit einem Defaultwert `0`. * `limit`, ein optionales `int`. -!!! tip "Tipp" - Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. +/// tip | "Tipp" + +Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index 67b5e3a87..cf44df5f0 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ Mit `File` können sie vom Client hochzuladende Dateien definieren. -!!! info - Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. - Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. +Z. B. `pip install python-multipart`. + +Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. + +/// ## `File` importieren Importieren Sie `File` und `UploadFile` von `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## `File`-Parameter definieren Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info -=== "Python 3.8+ nicht annotiert" +`File` ist eine Klasse, die direkt von `Form` erbt. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info - `File` ist eine Klasse, die direkt von `Form` erbt. +/// tip | "Tipp" - Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben +Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. -!!! tip "Tipp" - Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. +/// Die Dateien werden als „Formulardaten“ hochgeladen. @@ -79,26 +106,35 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// `UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: @@ -141,11 +177,17 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, contents = myfile.file.read() ``` -!!! note "Technische Details zu `async`" - Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. +/// note | "Technische Details zu `async`" + +Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. + +/// + +/// note | "Technische Details zu Starlette" -!!! note "Technische Details zu Starlette" - **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. +**FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. + +/// ## Was sind „Formulardaten“ @@ -153,82 +195,113 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -!!! note "Technische Details" - Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. +/// note | "Technische Details" + +Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + +Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +/// - Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. +/// warning | "Achtung" - Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. -!!! warning "Achtung" - Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Optionaler Datei-Upload Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` mit zusätzlichen Metadaten Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Mehrere Datei-Uploads @@ -238,76 +311,107 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.9+ nicht annotiert - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. -!!! note "Technische Details" - Sie können auch `from starlette.responses import HTMLResponse` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### Mehrere Datei-Uploads mit zusätzlichen Metadaten Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index 86b1406e6..e109595d1 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren. -!!! info - Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +/// ## `File` und `Form` importieren -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## `File` und `Form`-Parameter definieren Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. -!!! warning "Achtung" - Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. +/// warning | "Achtung" + +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 6c029b5fe..391788aff 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden. -!!! info - Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`. +/// info - Z. B. `pip install python-multipart`. +Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +/// ## `Form` importieren Importieren Sie `Form` von `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## `Form`-Parameter definieren Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. @@ -63,11 +84,17 @@ Die Spec erfordert, dass di Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw. -!!! info - `Form` ist eine Klasse, die direkt von `Body` erbt. +/// info + +`Form` ist eine Klasse, die direkt von `Body` erbt. + +/// + +/// tip | "Tipp" -!!! tip "Tipp" - Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. +Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +/// ## Über „Formularfelder“ @@ -75,17 +102,23 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -!!! note "Technische Details" - Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. +/// note | "Technische Details" + +Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + +Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +/// - Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. +/// warning | "Achtung" - Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. +Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. -!!! warning "Achtung" - Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. - Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. +/// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index d5b92e0f9..3f632b1cb 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ Sie können den Typ der ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI wird diesen Rückgabetyp verwenden, um: @@ -53,35 +59,47 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: * `@app.delete()` * usw. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note "Hinweis" - Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. +//// + +/// note | "Hinweis" + +Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. + +/// `response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`. FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. -!!! tip "Tipp" - Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. +/// tip | "Tipp" + +Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. + +So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. - So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. +/// ### `response_model`-Priorität @@ -95,37 +113,48 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +Um `EmailStr` zu verwenden, installieren Sie zuerst `email_validator`. -!!! info - Um `EmailStr` zu verwenden, installieren Sie zuerst `email_validator`. +Z. B. `pip install email-validator` +oder `pip install pydantic[email]`. - Z. B. `pip install email-validator` - oder `pip install pydantic[email]`. +/// Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. @@ -133,52 +162,67 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. -!!! danger "Gefahr" - Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. +/// danger | "Gefahr" + +Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. + +/// ## Ausgabemodell hinzufügen Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// ... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). @@ -202,17 +246,21 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. @@ -278,17 +326,21 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +//// ... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. @@ -300,17 +352,21 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` + +//// Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 @@ -318,23 +374,29 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d Ihr Responsemodell könnte Defaultwerte haben, wie: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. * `tax: float = 10.5` hat einen Defaultwert `10.5`. @@ -348,23 +410,29 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. @@ -377,21 +445,30 @@ Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wir } ``` -!!! info - In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +/// info + +FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen. - Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. +/// -!!! info - FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen. +/// info -!!! info - Sie können auch: +Sie können auch: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben. +verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben. + +/// #### Daten mit Werten für Felder mit Defaultwerten @@ -426,10 +503,13 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, Diese Felder werden also in der JSON-Response enthalten sein. -!!! tip "Tipp" - Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. +/// tip | "Tipp" + +Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. + +Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. - Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. +/// ### `response_model_include` und `response_model_exclude` @@ -439,45 +519,59 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. -!!! tip "Tipp" - Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. +/// tip | "Tipp" - Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. +Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. - Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. +Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. -=== "Python 3.10+" +Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -!!! tip "Tipp" - Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. +//// - Äquivalent zu `set(["name", "description"])`. +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +/// tip | "Tipp" + +Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. + +Äquivalent zu `set(["name", "description"])`. + +/// #### `list`en statt `set`s verwenden Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index a9cc238f8..5f96b83e4 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Hinweis" - Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. +/// note | "Hinweis" + +Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. + +/// Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben. -!!! info - Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`. +/// info + +Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`. + +/// Das wird: @@ -27,15 +33,21 @@ Das wird: -!!! note "Hinweis" - Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. +/// note | "Hinweis" + +Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. + +FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. - FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. +/// ## Über HTTP-Statuscodes -!!! note "Hinweis" - Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. +/// note | "Hinweis" + +Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode. @@ -54,8 +66,11 @@ Kurz: * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. * `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. -!!! tip "Tipp" - Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes. +/// tip | "Tipp" + +Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes. + +/// ## Abkürzung, um die Namen zu erinnern @@ -79,10 +94,13 @@ Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese -!!! note "Technische Details" - Sie können auch `from starlette import status` verwenden. +/// note | "Technische Details" + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. +/// ## Den Defaultwert ändern diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index e8bfc9876..07b4bb759 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ Hier sind mehrere Möglichkeiten, das zu tun. Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet. -=== "Pydantic v2" +//// tab | Pydantic v2 + +In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration. + +Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. - In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration. +//// - Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. +//// tab | Pydantic v1 -=== "Pydantic v1" +In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization. - In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization. +Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. - Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. +//// -!!! tip "Tipp" - Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. +/// tip | "Tipp" - Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. +Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. -!!! info - OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. +Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. - Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 +/// - Mehr erfahren Sie am Ende dieser Seite. +/// info + +OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. + +Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 + +Mehr erfahren Sie am Ende dieser Seite. + +/// ## Zusätzliche Argumente für `Field` Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## `examples` im JSON-Schema – OpenAPI @@ -92,41 +114,57 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Beispiel in der Dokumentations-Benutzeroberfläche @@ -138,41 +176,57 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: Sie können natürlich auch mehrere `examples` übergeben: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. @@ -213,41 +267,57 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: Sie können es so verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | "Tipp" - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche @@ -257,17 +327,23 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe ## Technische Details -!!! tip "Tipp" - Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. +/// tip | "Tipp" + +Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. + +Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. + +Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 - Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. +/// - Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 +/// warning | "Achtung" -!!! warning "Achtung" - Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. +Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. - Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. +Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. + +/// Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**. @@ -285,8 +361,11 @@ OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Sp * `File()` * `Form()` -!!! info - Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. +/// info + +Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. + +/// ### JSON Schemas Feld `examples` @@ -298,10 +377,13 @@ Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdef Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben). -!!! info - Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). +/// info + +Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). + +Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. - Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. +/// ### Pydantic- und FastAPI-`examples` diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 1e75fa8d9..6bc42cf6c 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -20,35 +20,47 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie Kopieren Sie das Beispiel in eine Datei `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// ## Ausführen -!!! info - Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. +/// info - Z. B. `pip install python-multipart`. +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. - Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. +Z. B. `pip install python-multipart`. + +Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. + +/// Führen Sie das Beispiel aus mit: @@ -70,17 +82,23 @@ Sie werden etwa Folgendes sehen: -!!! check "Authorize-Button!" - Sie haben bereits einen glänzenden, neuen „Authorize“-Button. +/// check | "Authorize-Button!" + +Sie haben bereits einen glänzenden, neuen „Authorize“-Button. - Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. +Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. + +/// Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder): -!!! note "Hinweis" - Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. +/// note | "Hinweis" + +Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. + +/// Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren. @@ -122,53 +140,71 @@ Betrachten wir es also aus dieser vereinfachten Sicht: In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`. -!!! info - Ein „Bearer“-Token ist nicht die einzige Option. +/// info + +Ein „Bearer“-Token ist nicht die einzige Option. + +Aber es ist die beste für unseren Anwendungsfall. - Aber es ist die beste für unseren Anwendungsfall. +Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. - Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. +In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. - In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. +/// Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -!!! tip "Tipp" - Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. +/// tip | "Tipp" - Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip | "Tipp" + +Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. + +Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. + +Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. + +/// Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet. Wir werden demnächst auch die eigentliche Pfadoperation erstellen. -!!! info - Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. +/// info + +Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. + +Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. - Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. +/// Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“. @@ -184,35 +220,47 @@ Es kann also mit `Depends` verwendet werden. Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. **FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. -!!! info "Technische Details" - **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. +/// info | "Technische Details" + +**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. + +Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. - Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. +/// ## Was es macht diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 09b55a20e..8a68deeef 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -2,26 +2,35 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Aber das ist immer noch nicht so nützlich. @@ -33,41 +42,57 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell. So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 13-17" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="5 13-17" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Eine `get_current_user`-Abhängigkeit erstellen @@ -79,135 +104,189 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="26" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="26" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Den Benutzer holen `get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +```Python hl_lines="20-23 27-28" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20-23 27-28" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Den aktuellen Benutzer einfügen Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="32" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="32" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. -!!! tip "Tipp" - Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. +/// tip | "Tipp" - Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. +Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. -!!! check - Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. +Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. - Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. +/// + +/// check + +Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. + +Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. + +/// ## Andere Modelle @@ -241,41 +320,57 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31-33" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="31-33" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md index 7a11e704d..ad0927361 100644 --- a/docs/de/docs/tutorial/security/index.md +++ b/docs/de/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet. OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. -!!! tip "Tipp" - Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. +/// tip | "Tipp" +Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI definiert die folgenden Sicherheitsschemas: * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. -!!! tip "Tipp" - Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. +/// tip | "Tipp" + +Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. + +Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. - Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. +/// ## **FastAPI** Tools diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 9f43cccc9..88f0dbe42 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" Hier verwenden wir das empfohlene: pyca/cryptography. -!!! tip "Tipp" - Dieses Tutorial verwendete zuvor PyJWT. +/// tip | "Tipp" - Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. +Dieses Tutorial verwendete zuvor PyJWT. + +Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. + +/// ## Passwort-Hashing @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" -!!! tip "Tipp" - Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. +/// tip | "Tipp" + +Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. - So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. +So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. - Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. +Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. + +/// ## Die Passwörter hashen und überprüfen @@ -96,12 +102,15 @@ Importieren Sie die benötigten Tools aus `passlib`. Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. -!!! tip "Tipp" - Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. +/// tip | "Tipp" + +Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. - Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. +Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. - Und mit allen gleichzeitig kompatibel sein. +Und mit allen gleichzeitig kompatibel sein. + +/// Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen. @@ -109,44 +118,63 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | "Tipp" - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="7 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +```Python hl_lines="6 47 54-55 58-59 68-74" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// note | "Hinweis" - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. -!!! note "Hinweis" - Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// ## JWT-Token verarbeiten @@ -176,41 +204,57 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="6 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="5 11-13 27-29 77-85" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="6 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## Die Abhängigkeiten aktualisieren @@ -220,41 +264,57 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="88-105" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ## Die *Pfadoperation* `/token` aktualisieren @@ -262,41 +322,57 @@ Erstellen Sie ein `timedelta` mit der Ablaufz Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="117-132" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// - ```Python hl_lines="117-132" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="117-132" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="117-132" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="114-129" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ### Technische Details zum JWT-„Subjekt“ `sub` @@ -335,8 +411,11 @@ Verwenden Sie die Anmeldeinformationen: Benutzername: `johndoe` Passwort: `secret`. -!!! check - Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. +/// check + +Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. + +/// @@ -357,8 +436,11 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat -!!! note "Hinweis" - Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. +/// note | "Hinweis" + +Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. + +/// ## Fortgeschrittene Verwendung mit `scopes` diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index ed280d486..3b1c4ae28 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu * `instagram_basic` wird von Facebook / Instagram verwendet. * `https://www.googleapis.com/auth/drive` wird von Google verwendet. -!!! info - In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. +/// info - Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. - Diese Details sind implementierungsspezifisch. +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. - Für OAuth2 sind es einfach nur Strings. +Diese Details sind implementierungsspezifisch. + +Für OAuth2 sind es einfach nur Strings. + +/// ## Code, um `username` und `password` entgegenzunehmen. @@ -49,41 +52,57 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.9+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="4 79" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// `OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: @@ -92,29 +111,38 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A * Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. * Einem optionalen `grant_type` („Art der Anmeldung“). -!!! tip "Tipp" - Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. +/// tip | "Tipp" + +Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. - Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. +Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. + +/// * Eine optionale `client_id` (benötigen wir für unser Beispiel nicht). * Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht). -!!! info - `OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. - `OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. +Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. - Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. +Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. - Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. +/// ### Die Formulardaten verwenden -!!! tip "Tipp" - Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. +/// tip | "Tipp" + +Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. + +In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. - In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. +/// Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld. @@ -122,41 +150,57 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u Für den Fehler verwenden wir die Exception `HTTPException`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 80-82" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="3 80-82" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +/// + +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// ### Das Passwort überprüfen @@ -182,41 +226,57 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="83-86" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="83-86" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// #### Über `**user_dict` @@ -234,8 +294,11 @@ UserInDB( ) ``` -!!! info - Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. +/// info + +Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. + +/// ## Den Token zurückgeben @@ -247,55 +310,77 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. -!!! tip "Tipp" - Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. +/// tip | "Tipp" + +Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. + +Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. - Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="88" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +```Python hl_lines="88" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip | "Tipp" -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` -!!! tip "Tipp" - Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. +//// - Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` - Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. +//// - Den Rest erledigt **FastAPI** für Sie. +/// tip | "Tipp" + +Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. + +Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. + +Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. + +Den Rest erledigt **FastAPI** für Sie. + +/// ## Die Abhängigkeiten aktualisieren @@ -309,56 +394,75 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="59-67 70-75 95" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | "Tipp" - ```Python hl_lines="56-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// info - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. -!!! info - Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. +Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. - Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. +Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. - Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. +Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. - Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. +Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. - Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. +Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. - Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. +Das ist der Vorteil von Standards ... - Das ist der Vorteil von Standards ... +/// ## Es in Aktion sehen diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index 1e289e120..cca8cd0ea 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Technische Details" - Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. +/// note | "Technische Details" - **FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. +Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. + +**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +/// ### Was ist „Mounten“? diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 541cc1bf0..43ced2aae 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -8,10 +8,13 @@ Damit können Sie `httpx`. +/// info - Z. B. `pip install httpx`. +Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`. + +Z. B. `pip install httpx`. + +/// Importieren Sie `TestClient`. @@ -27,20 +30,29 @@ Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. +/// tip | "Tipp" + +Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. + +Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. + +Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. + +/// + +/// note | "Technische Details" + +Sie könnten auch `from starlette.testclient import TestClient` verwenden. - Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. +**FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. - Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. +/// -!!! note "Technische Details" - Sie könnten auch `from starlette.testclient import TestClient` verwenden. +/// tip | "Tipp" - **FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. +Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. -!!! tip "Tipp" - Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. +/// ## Tests separieren @@ -110,41 +122,57 @@ Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnt Beide *Pfadoperationen* erfordern einen `X-Token`-Header. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | "Tipp" - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | "Tipp" + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Erweiterte Testdatei @@ -168,10 +196,13 @@ Z. B.: Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der HTTPX-Dokumentation. -!!! info - Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. +/// info + +Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. + +Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. - Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. +/// ## Tests ausführen diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index 26963c2e3..7a70718c5 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # 🌖 📨 🗄 -!!! warning - 👉 👍 🏧 ❔. +/// warning - 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. +👉 👍 🏧 ❔. + +🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. + +/// 👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️. @@ -27,20 +30,26 @@ {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note - ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. +/// note + +✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. + +/// + +/// info -!!! info - `model` 🔑 🚫 🍕 🗄. +`model` 🔑 🚫 🍕 🗄. - **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. +**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. - ☑ 🥉: +☑ 🥉: - * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: - * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: - * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. - * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩‍💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. +* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: + * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: + * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. + * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩‍💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. + +/// 🏗 📨 🗄 👉 *➡ 🛠️* 🔜: @@ -172,13 +181,19 @@ {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note - 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. +/// note + +👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. + +/// + +/// info + +🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). -!!! info - 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). +✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨‍💼 🏷. - ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨‍💼 🏷. +/// ## 🌀 ℹ diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 392579df6..3f3b0aea4 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning - 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. +/// warning - ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. +🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. - ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). +⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. + +/// ## 🗄 & 🛠️ 🩺 diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index fa1554734..22044c783 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -60,11 +60,14 @@ checker(q="somequery") {!../../../docs_src/dependencies/tutorial011.py!} ``` -!!! tip - 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. +/// tip - 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. +🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. - 📃 🔃 💂‍♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. +👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. - 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂‍♂ 👷 🔘. +📃 🔃 💂‍♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. + +🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂‍♂ 👷 🔘. + +/// diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index df94c6ce7..324b4f68a 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ $ pytest {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip - 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. +/// tip + +🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. + +/// ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. @@ -81,12 +84,18 @@ response = client.get('/') ...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ `TestClient`. -!!! tip - 🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. +/// tip + +🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. + +/// ## 🎏 🔁 🔢 🤙 🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& `await`) 🎏 `async` 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟. -!!! tip - 🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. +/// tip + +🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. + +/// diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index e3fd26735..bb65e1487 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -39,8 +39,11 @@ browser --> proxy proxy --> server ``` -!!! tip - 📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. +/// tip + +📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. + +/// 🩺 🎚 🔜 💪 🗄 🔗 📣 👈 👉 🛠️ `server` 🔎 `/api/v1` (⛅ 🗳). 🖼: @@ -77,10 +80,13 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`. -!!! note "📡 ℹ" - 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. +/// note | "📡 ℹ" + +🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. + + & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. - & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. +/// ### ✅ ⏮️ `root_path` @@ -168,8 +174,11 @@ Uvicorn 🔜 ⌛ 🗳 🔐 Uvicorn `http://127.0.0.1:8000/app`, & ⤴️ ⚫ 👉 💬 Traefik 👂 🔛 ⛴ 9️⃣9️⃣9️⃣9️⃣ & ⚙️ ➕1️⃣ 📁 `routes.toml`. -!!! tip - 👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. +/// tip + +👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. + +/// 🔜 ✍ 👈 🎏 📁 `routes.toml`: @@ -235,8 +244,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. +/// tip + +👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. + +/// & 🔜 📂 📛 ⏮️ ⛴ Traefik, ✅ ➡ 🔡: http://127.0.0.1:9999/api/v1/app. @@ -279,8 +291,11 @@ $ uvicorn main:app --root-path /api/v1 ## 🌖 💽 -!!! warning - 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. +/// warning + +👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. + +/// 🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`. @@ -319,15 +334,21 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. +/// tip + +👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. + +/// 🩺 🎚 http://127.0.0.1:9999/api/v1/docs ⚫️ 🔜 👀 💖: -!!! tip - 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. +/// tip + +🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. + +/// ### ❎ 🏧 💽 ⚪️➡️ `root_path` diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index cf76c01d0..eec87b91b 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ & 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨‍🎨*. -!!! note - 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅‍♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅‍♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. +/// note + +🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅‍♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅‍♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. + +/// ## ⚙️ `ORJSONResponse` @@ -31,15 +34,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +/// info + +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. + +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. + + & ⚫️ 🔜 📄 ✅ 🗄. + +/// - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. +/// tip - & ⚫️ 🔜 📄 ✅ 🗄. +`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. -!!! tip - `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. +/// ## 🕸 📨 @@ -52,12 +61,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +/// info - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. - & ⚫️ 🔜 📄 ✅ 🗄. +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. + + & ⚫️ 🔜 📄 ✅ 🗄. + +/// ### 📨 `Response` @@ -69,11 +81,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning - `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. +/// warning + +`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. + +/// + +/// info -!!! info - ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. +↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. + +/// ### 📄 🗄 & 🔐 `Response` @@ -103,10 +121,13 @@ ✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### `Response` @@ -153,15 +174,21 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎛 🎻 📨 ⚙️ `ujson`. -!!! warning - `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. +/// warning + +`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip - ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. +/// tip + +⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. + +/// ### `RedirectResponse` @@ -222,8 +249,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁. -!!! tip - 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕‍🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. +/// tip + +👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕‍🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. + +/// ### `FileResponse` @@ -292,8 +322,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip - 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. +/// tip + +👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. + +/// ## 🌖 🧾 diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index e8c4b99a2..3f49ef07c 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic. -!!! info - ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. +/// info - , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. +✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. - ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 +, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. + +✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 + +/// ## 🎻 `response_model` diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 19421ff58..12c902c18 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -38,10 +38,13 @@ & ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻. -!!! tip - `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. +/// tip - 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 +`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. + +🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 + +/// ### 🔆 🔢 @@ -91,10 +94,13 @@ async with lifespan(app): ## 🎛 🎉 (😢) -!!! warning - 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. +/// warning + +👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. - 👆 💪 🎲 🚶 👉 🍕. +👆 💪 🎲 🚶 👉 🍕. + +/// 📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*. @@ -126,20 +132,29 @@ async with lifespan(app): 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. -!!! info - `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. +/// info + +`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. + +/// + +/// tip + +👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. + +, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. + +✋️ `open()` 🚫 ⚙️ `async` & `await`. -!!! tip - 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. +, 👥 📣 🎉 🐕‍🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. - , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. +/// - ✋️ `open()` 🚫 ⚙️ `async` & `await`. +/// info - , 👥 📣 🎉 🐕‍🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. +👆 💪 ✍ 🌅 🔃 👫 🎉 🐕‍🦺 💃 🎉' 🩺. -!!! info - 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕‍🦺 💃 🎉' 🩺. +/// ### `startup` & `shutdown` 👯‍♂️ diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index 261f9fb61..c8e044340 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -16,17 +16,21 @@ ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +//// 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app -!!! tip - 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. +/// tip + +👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. + +/// 👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨: @@ -129,17 +136,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩‍💻**, & 👫 💪 👽 🔖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` + +//// - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// ### 🏗 📕 👩‍💻 ⏮️ 🔖 @@ -186,17 +197,21 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶‍♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// ### 🏗 📕 👩‍💻 ⏮️ 🛃 🛠️ 🆔 diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md index 43bada6b4..48ef8e46d 100644 --- a/docs/em/docs/advanced/index.md +++ b/docs/em/docs/advanced/index.md @@ -6,10 +6,13 @@ ⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index b3e722ed0..89f494aa3 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫. -!!! note "📡 ℹ" - ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. +/// note | "📡 ℹ" - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 3355d6071..00d54ebec 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. +/// tip + +`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. + +/// 🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨‍🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭. @@ -61,10 +64,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕. -!!! tip - ☑ ⏲ 🇺🇸🔍 📨. +/// tip + +☑ ⏲ 🇺🇸🔍 📨. - 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨. +🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨. + +/// ## ✍ ⏲ 🧾 📟 @@ -74,10 +80,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙). -!!! tip - 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩‍💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. +/// tip + +🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩‍💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. - 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩‍💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. +🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩‍💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. + +/// ### ✍ ⏲ `APIRouter` @@ -154,8 +163,11 @@ https://www.external.org/events/invoices/2expen51ve } ``` -!!! tip - 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). +/// tip + +👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). + +/// ### 🚮 ⏲ 📻 @@ -167,8 +179,11 @@ https://www.external.org/events/invoices/2expen51ve {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - 👀 👈 👆 🚫 🚶‍♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. +/// tip + +👀 👈 👆 🚫 🚶‍♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. + +/// ### ✅ 🩺 diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 3dc5ac536..b684df26f 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## 🗄 { -!!! warning - 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. +/// warning + +🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. + +/// 👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`. @@ -23,13 +26,19 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. +/// tip + +🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. + +/// + +/// warning + +🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. -!!! warning - 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. +🚥 👫 🎏 🕹 (🐍 📁). - 🚥 👫 🎏 🕹 (🐍 📁). +/// ## 🚫 ⚪️➡️ 🗄 @@ -65,8 +74,11 @@ 🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗. -!!! note "📡 ℹ" - 🗄 🔧 ⚫️ 🤙 🛠️ 🎚. +/// note | "📡 ℹ" + +🗄 🔧 ⚫️ 🤙 🛠️ 🎚. + +/// ⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾. @@ -74,10 +86,13 @@ 👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️. -!!! tip - 👉 🔅 🎚 ↔ ☝. +/// tip + +👉 🔅 🎚 ↔ ☝. - 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. +🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. + +/// 👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`. @@ -164,7 +179,10 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` -!!! tip - 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. +/// tip + +📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. + +✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. - ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. +/// diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 23fffe1dd..717fb87ce 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. +/// tip - , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. +✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. - & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. +, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. + + & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. + +/// ### 🌅 ℹ -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +/// 👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃. diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index ba09734fb..13ee081c2 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️. -!!! tip - `JSONResponse` ⚫️ 🎧-🎓 `Response`. +/// tip + +`JSONResponse` ⚫️ 🎧-🎓 `Response`. + +/// & 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶‍♀️ ⚫️ 🔗. @@ -35,10 +38,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ## 🛬 🛃 `Response` diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index de798982a..27e1cdbd5 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. + +/// ## 🛃 🎚 diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md index 10291338e..5cdc47505 100644 --- a/docs/em/docs/advanced/security/index.md +++ b/docs/em/docs/advanced/security/index.md @@ -4,10 +4,13 @@ 📤 ➕ ⚒ 🍵 💂‍♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩‍💻 🦮: 💂‍♂](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index d82fe152b..73b2ec540 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕‍🦺, 💖 👱📔 👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸. -!!! warning - 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. +/// warning - 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. +👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. - ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. +👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. - 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂‍♂/✔ 📄, 👐 👆 💪, 👆 📟. +✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. - 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. +👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂‍♂/✔ 📄, 👐 👆 💪, 👆 📟. - ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. +📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. + +✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. + +/// ## Oauth2️⃣ ↔ & 🗄 @@ -43,14 +46,17 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info + +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. + +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +👈 ℹ 🛠️ 🎯. - 👈 ℹ 🛠️ 🎯. +Oauth2️⃣ 👫 🎻. - Oauth2️⃣ 👫 🎻. +/// ## 🌐 🎑 @@ -88,10 +94,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. & 👥 📨 ↔ 🍕 🥙 🤝. -!!! danger - 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. +/// danger - ✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. +🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. + +✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. + +/// ```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} @@ -113,21 +122,27 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔). -!!! note - 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. +/// note + +👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. - 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. +👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. + +/// ```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` -!!! info "📡 ℹ" - `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. +/// info | "📡 ℹ" + +`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. - ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂‍♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. +✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂‍♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. - ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// ## ⚙️ `SecurityScopes` @@ -216,10 +231,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`. * `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯‍♂️. -!!! tip - ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. +/// tip + +⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. - 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. +🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. + +/// ## 🌖 ℹ 🔃 `SecurityScopes` @@ -257,10 +275,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕‍🦺 🔚 🆙 ✔ 🔑 💧. -!!! note - ⚫️ ⚠ 👈 🔠 🤝 🐕‍🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. +/// note + +⚫️ ⚠ 👈 🔠 🤝 🐕‍🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. + +✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. - ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. +/// **FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`. diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index c17212023..e84941b57 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 🌐 🔢 -!!! tip - 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. +/// tip + +🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. + +/// 🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃‍♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍). 👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆‍♂ 🐍: -=== "💾, 🇸🇻, 🚪 🎉" +//// tab | 💾, 🇸🇻, 🚪 🎉 + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" -
+// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" - ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" +
- Hello Wade Wilson - ``` +//// -
+//// tab | 🚪 📋 -=== "🚪 📋" +
-
+```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### ✍ 🇨🇻 {🐍 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - 🥈 ❌ `os.getenv()` 🔢 💲 📨. +/// tip + +🥈 ❌ `os.getenv()` 🔢 💲 📨. - 🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. +🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. + +/// ⤴️ 👆 💪 🤙 👈 🐍 📋: @@ -114,8 +124,11 @@ Hello World from Python -!!! tip - 👆 💪 ✍ 🌅 🔃 ⚫️ 1️⃣2️⃣-⚖ 📱: 📁. +/// tip + +👆 💪 ✍ 🌅 🔃 ⚫️ 1️⃣2️⃣-⚖ 📱: 📁. + +/// ### 🆎 & 🔬 @@ -139,8 +152,11 @@ Hello World from Python {!../../../docs_src/settings/tutorial001.py!} ``` -!!! tip - 🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. +/// tip + +🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. + +/// ⤴️, 🕐❔ 👆 ✍ 👐 👈 `Settings` 🎓 (👉 💼, `settings` 🎚), Pydantic 🔜 ✍ 🌐 🔢 💼-😛 🌌,, ↖-💼 🔢 `APP_NAME` 🔜 ✍ 🔢 `app_name`. @@ -168,8 +184,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -!!! tip - ⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. +/// tip + +⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. + +/// & ⤴️ `admin_email` ⚒ 🔜 ⚒ `"deadpool@example.com"`. @@ -193,8 +212,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - 👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// tip + +👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## ⚒ 🔗 @@ -220,10 +242,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app {!../../../docs_src/settings/app02/main.py!} ``` -!!! tip - 👥 🔜 🔬 `@lru_cache` 🍖. +/// tip + +👥 🔜 🔬 `@lru_cache` 🍖. - 🔜 👆 💪 🤔 `get_settings()` 😐 🔢. +🔜 👆 💪 🤔 `get_settings()` 😐 🔢. + +/// & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. @@ -249,15 +274,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👉 💡 ⚠ 🥃 👈 ⚫️ ✔️ 📛, 👫 🌐 🔢 🛎 🥉 📁 `.env`, & 📁 🤙 "🇨🇻". -!!! tip - 📁 ▶️ ⏮️ ❣ (`.`) 🕵‍♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. +/// tip + +📁 ▶️ ⏮️ ❣ (`.`) 🕵‍♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. - ✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. +✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. + +/// Pydantic ✔️ 🐕‍🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕‍🦺. -!!! tip - 👉 👷, 👆 💪 `pip install python-dotenv`. +/// tip + +👉 👷, 👆 💪 `pip install python-dotenv`. + +/// ### `.env` 📁 @@ -278,8 +309,11 @@ APP_NAME="ChimichangApp" 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. -!!! tip - `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 +/// tip + +`Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 + +/// ### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache` diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 0a73a4f47..c45ff47a1 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -31,16 +31,25 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - 👀 👈 👆 ✔️ 🚶‍♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. +/// note -!!! tip - 📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. +👀 👈 👆 ✔️ 🚶‍♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. +/// - **FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. +/// tip + +📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. + +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. + +**FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. + +/// ## ✍ 📄 diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md index 93acd710e..825d545a9 100644 --- a/docs/em/docs/advanced/testing-database.md +++ b/docs/em/docs/advanced/testing-database.md @@ -52,10 +52,13 @@ {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - 👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯‍♂️ `database.py` & `tests/test_sql_app.py`. +/// tip - 🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. +👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯‍♂️ `database.py` & `tests/test_sql_app.py`. + +🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. + +/// ## ✍ 💽 @@ -81,8 +84,11 @@ Base.metadata.create_all(bind=engine) {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - 📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. +/// tip + +📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. + +/// ## 💯 📱 diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 104a6325e..8bcffcc29 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -32,12 +32,15 @@ {!../../../docs_src/dependency_testing/tutorial001.py!} ``` -!!! tip - 👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. +/// tip - ⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨‍🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. +👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. - FastAPI 🔜 💪 🔐 ⚫️. +⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨‍🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. + +FastAPI 🔜 💪 🔐 ⚫️. + +/// ⤴️ 👆 💪 ⏲ 👆 🔐 (❎ 👫) ⚒ `app.dependency_overrides` 🛁 `dict`: @@ -45,5 +48,8 @@ app.dependency_overrides = {} ``` -!!! tip - 🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). +/// tip + +🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). + +/// diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 3b8e7e420..5fb1e9c34 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note - 🌅 ℹ, ✅ 💃 🧾 🔬 *️⃣ . +/// note + +🌅 ℹ, ✅ 💃 🧾 🔬 *️⃣ . + +/// diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index faeadb1aa..edc951d96 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. -!!! tip - 🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. +/// tip - , ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. +🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. - 🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁‍♂️. +, ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. + +🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁‍♂️. + +/// ## `Request` 🧾 👆 💪 ✍ 🌅 ℹ 🔃 `Request` 🎚 🛂 💃 🧾 🕸. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.requests import Request`. + +**FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 6ba9b999d..30dc3043e 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -50,10 +50,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.websockets import WebSocket`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.websockets import WebSocket`. + +**FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. + +/// ## ⌛ 📧 & 📨 📧 @@ -116,10 +119,13 @@ $ uvicorn main:app --reload {!../../../docs_src/websockets/tutorial002.py!} ``` -!!! info - 👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. +/// info + +👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. + +👆 💪 ⚙️ 📪 📟 ⚪️➡️ ☑ 📟 🔬 🔧. - 👆 💪 ⚙️ 📪 📟 ⚪️➡️ ☑ 📟 🔬 🔧. +/// ### 🔄 *️⃣ ⏮️ 🔗 @@ -142,8 +148,11 @@ $ uvicorn main:app --reload * "🏬 🆔", ⚙️ ➡. * "🤝" ⚙️ 🔢 🔢. -!!! tip - 👀 👈 🔢 `token` 🔜 🍵 🔗. +/// tip + +👀 👈 🔢 `token` 🔜 🍵 🔗. + +/// ⏮️ 👈 👆 💪 🔗 *️⃣ & ⤴️ 📨 & 📨 📧: @@ -169,12 +178,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. +/// tip + +📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. + +✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. - ✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. +🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕‍🦺 ✳, ✳ ⚖️ 🎏, ✅ 🗜/📻. - 🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕‍🦺 ✳, ✳ ⚖️ 🎏, ✅ 🗜/📻. +/// ## 🌅 ℹ diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 5890b3b13..334c0de73 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -30,12 +30,17 @@ ⚫️ 🕐 🥇 🖼 **🏧 🛠️ 🧾**, & 👉 🎯 🕐 🥇 💭 👈 😮 "🔎" **FastAPI**. -!!! note - ✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. +/// note +✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. -!!! check "😮 **FastAPI** " - ✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. +/// + +/// check | "😮 **FastAPI** " + +✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. + +/// ### 🏺 @@ -51,11 +56,13 @@ 👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺. -!!! check "😮 **FastAPI** " - ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +/// check | "😮 **FastAPI** " - ✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. +◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. + +/// ### 📨 @@ -91,11 +98,13 @@ def read_url(): 👀 🔀 `requests.get(...)` & `@app.get(...)`. -!!! check "😮 **FastAPI** " - * ✔️ 🙅 & 🏋️ 🛠️. - * ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. - * ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// check | "😮 **FastAPI** " + +* ✔️ 🙅 & 🏋️ 🛠️. +* ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. +* ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// ### 🦁 / 🗄 @@ -109,15 +118,18 @@ def read_url(): 👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄". -!!! check "😮 **FastAPI** " - 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. +/// check | "😮 **FastAPI** " + +🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. - & 🛠️ 🐩-⚓️ 👩‍💻 🔢 🧰: + & 🛠️ 🐩-⚓️ 👩‍💻 🔢 🧰: - * 🦁 🎚 - * 📄 +* 🦁 🎚 +* 📄 - 👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩‍💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). +👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩‍💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). + +/// ### 🏺 🎂 🛠️ @@ -135,8 +147,11 @@ def read_url(): ✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 🔗 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭. -!!! check "😮 **FastAPI** " - ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. +/// check | "😮 **FastAPI** " + +⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. + +/// ### Webarg @@ -148,11 +163,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 👑 🧰 & 👤 ✔️ ⚙️ ⚫️ 📚 💁‍♂️, ⏭ ✔️ **FastAPI**. -!!! info - Webarg ✍ 🎏 🍭 👩‍💻. +/// info + +Webarg ✍ 🎏 🍭 👩‍💻. + +/// + +/// check | "😮 **FastAPI** " -!!! check "😮 **FastAPI** " - ✔️ 🏧 🔬 📨 📨 💽. +✔️ 🏧 🔬 📨 📨 💽. + +/// ### APISpec @@ -172,12 +193,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 👨‍🎨 💪 🚫 ℹ 🌅 ⏮️ 👈. & 🚥 👥 🔀 🔢 ⚖️ 🍭 🔗 & 💭 🔀 👈 📁#️⃣, 🏗 🔗 🔜 ❌. -!!! info - APISpec ✍ 🎏 🍭 👩‍💻. +/// info + +APISpec ✍ 🎏 🍭 👩‍💻. + +/// +/// check | "😮 **FastAPI** " -!!! check "😮 **FastAPI** " - 🐕‍🦺 📂 🐩 🛠️, 🗄. +🐕‍🦺 📂 🐩 🛠️, 🗄. + +/// ### 🏺-Apispec @@ -199,11 +225,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. & 👫 🎏 🌕-📚 🚂 🧢 [**FastAPI** 🏗 🚂](project-generation.md){.internal-link target=_blank}. -!!! info - 🏺-Apispec ✍ 🎏 🍭 👩‍💻. +/// info + +🏺-Apispec ✍ 🎏 🍭 👩‍💻. + +/// -!!! check "😮 **FastAPI** " - 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. +/// check | "😮 **FastAPI** " + +🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. + +/// ### NestJS (& 📐) @@ -219,24 +251,33 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔. -!!! check "😮 **FastAPI** " - ⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. +/// check | "😮 **FastAPI** " + +⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. - ✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. +✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. + +/// ### 🤣 ⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺. -!!! note "📡 ℹ" - ⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. +/// note | "📡 ℹ" + +⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. - ⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. +⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. -!!! check "😮 **FastAPI** " - 🔎 🌌 ✔️ 😜 🎭. +/// - 👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). +/// check | "😮 **FastAPI** " + +🔎 🌌 ✔️ 😜 🎭. + +👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). + +/// ### 🦅 @@ -246,12 +287,15 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. , 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢. -!!! check "😮 **FastAPI** " - 🔎 🌌 🤚 👑 🎭. +/// check | "😮 **FastAPI** " - ⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. +🔎 🌌 🤚 👑 🎭. - 👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. +⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. + +👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. + +/// ### @@ -269,10 +313,13 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨‍🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗. -!!! check "😮 **FastAPI** " - 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. +/// check | "😮 **FastAPI** " + +🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. - 👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕‍🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). +👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕‍🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). + +/// ### 🤗 @@ -288,15 +335,21 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ ⚓️ 🔛 ⏮️ 🐩 🔁 🐍 🕸 🛠️ (🇨🇻), ⚫️ 💪 🚫 🍵 *️⃣ & 🎏 👜, 👐 ⚫️ ✔️ ↕ 🎭 💁‍♂️. -!!! info - 🤗 ✍ ✡ 🗄, 🎏 👼 `isort`, 👑 🧰 🔁 😇 🗄 🐍 📁. +/// info + +🤗 ✍ ✡ 🗄, 🎏 👼 `isort`, 👑 🧰 🔁 😇 🗄 🐍 📁. + +/// -!!! check "💭 😮 **FastAPI**" - 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. +/// check | "💭 😮 **FastAPI**" - 🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. +🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. - 🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. +🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. + +🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. + +/// ### APIStar (<= 0️⃣.5️⃣) @@ -322,23 +375,29 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🔜 APIStar ⚒ 🧰 ✔ 🗄 🔧, 🚫 🕸 🛠️. -!!! info - APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: +/// info + +APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: - * ✳ 🎂 🛠️ - * 💃 (❔ **FastAPI** ⚓️) - * Uvicorn (⚙️ 💃 & **FastAPI**) +* ✳ 🎂 🛠️ +* 💃 (❔ **FastAPI** ⚓️) +* Uvicorn (⚙️ 💃 & **FastAPI**) -!!! check "😮 **FastAPI** " - 🔀. +/// - 💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨‍🎨 🐕‍🦺, 🕳 👤 🤔 💎 💭. +/// check | "😮 **FastAPI** " - & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. +🔀. - ⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. +💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨‍🎨 🐕‍🦺, 🕳 👤 🤔 💎 💭. - 👤 🤔 **FastAPI** "🛐 👨‍💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. + +⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. + +👤 🤔 **FastAPI** "🛐 👨‍💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + +/// ## ⚙️ **FastAPI** @@ -350,10 +409,13 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 ⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨‍🎨 🐕‍🦺 👑. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). +/// check | "**FastAPI** ⚙️ ⚫️" - **FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. +🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). + +**FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. + +/// ### 💃 @@ -382,17 +444,23 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂‍♂ 🚙, 🗄 🔗 ⚡, ♒️. -!!! note "📡 ℹ" - 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. +/// note | "📡 ℹ" + +🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. - 👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. +👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. +/// - 🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. +/// check | "**FastAPI** ⚙️ ⚫️" - , 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. +🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. + +🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. + +, 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. + +/// ### Uvicorn @@ -402,12 +470,15 @@ Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. ⚫️ 👍 💽 💃 & **FastAPI**. -!!! check "**FastAPI** 👍 ⚫️" - 👑 🕸 💽 🏃 **FastAPI** 🈸. +/// check | "**FastAPI** 👍 ⚫️" + +👑 🕸 💽 🏃 **FastAPI** 🈸. + +👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. - 👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. +✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. - ✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. +/// ## 📇 & 🚅 diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index 0db497f40..ac9804f64 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. +/// note + +👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. + +/// --- @@ -136,8 +139,11 @@ def results(): -!!! info - 🌹 🖼 👯 🍏. 👶 +/// info + +🌹 🖼 👯 🍏. 👶 + +/// --- @@ -199,8 +205,11 @@ def results(): 📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶 -!!! info - 🌹 🖼 👯 🍏. 👶 +/// info + +🌹 🖼 👯 🍏. 👶 + +/// --- @@ -392,12 +401,15 @@ async def read_burgers(): ## 📶 📡 ℹ -!!! warning - 👆 💪 🎲 🚶 👉. +/// warning + +👆 💪 🎲 🚶 👉. + +👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. - 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. +🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. - 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. +/// ### ➡ 🛠️ 🔢 diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md index 08561d8f8..3ac1afda4 100644 --- a/docs/em/docs/contributing.md +++ b/docs/em/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env 🔓 🆕 🌐 ⏮️: -=== "💾, 🇸🇻" +//// tab | 💾, 🇸🇻 -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "🚪 📋" +//// -
+//// tab | 🚪 📋 - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "🚪 🎉" +
- ⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ 🐛 🎉): +//// -
+//// tab | 🚪 🎉 - ```console - $ source ./env/Scripts/activate - ``` +⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ 🐛 🎉): -
+
+ +```console +$ source ./env/Scripts/activate +``` + +
+ +//// ✅ ⚫️ 👷, ⚙️: -=== "💾, 🇸🇻, 🚪 🎉" +//// tab | 💾, 🇸🇻, 🚪 🎉 -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "🚪 📋" +//// -
+//// tab | 🚪 📋 - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip -
+some/directory/fastapi/env/bin/pip +``` + +
+ +//// 🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip - 🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. +/// tip + +🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. - 👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. +👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. + +/// ### 🐖 @@ -149,8 +162,11 @@ $ bash scripts/format.sh & 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`. -!!! tip - 👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. +/// tip + +👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. + +/// 🌐 🧾 ✍ 📁 📁 `./docs/en/`. @@ -235,10 +251,13 @@ Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. * ✅ ⏳ ♻ 🚲 📨 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. -!!! tip - 👆 💪 🚮 🏤 ⏮️ 🔀 🔑 ♻ 🚲 📨. +/// tip + +👆 💪 🚮 🏤 ⏮️ 🔀 🔑 ♻ 🚲 📨. + +✅ 🩺 🔃 ❎ 🚲 📨 📄 ✔ ⚫️ ⚖️ 📨 🔀. - ✅ 🩺 🔃 ❎ 🚲 📨 📄 ✔ ⚫️ ⚖️ 📨 🔀. +/// * ✅ 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. @@ -260,8 +279,11 @@ Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. 💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`. -!!! tip - 👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. +/// tip + +👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. + +/// 🔜 🏃 🖖 💽 🩺 🇪🇸: @@ -298,8 +320,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - 👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. +/// tip + +👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. + +/// * 🔜 📂 ⬜ 📁 📁 🇪🇸: @@ -370,10 +395,13 @@ Updating en 🔜 👆 💪 ✅ 👆 📟 👨‍🎨 ⏳ ✍ 📁 `docs/ht/`. -!!! tip - ✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. +/// tip + +✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. + +👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 - 👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 +/// ▶️ ✍ 👑 📃, `docs/ht/index.md`. diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index b0f86cb5e..019703296 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -151,10 +151,13 @@ ✋️ 👈 💼 ⏮️ 🤙 👎 ❌ 👈 💥 🏃‍♂ **🛠️**, 👆 🔜 💚 🔢 🦲 👈 🈚 **🔁** 🛠️, 🌘 👩‍❤‍👨 🕰... -!!! tip - ...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. +/// tip - ➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. +...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. + +➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. + +/// 👆 🔜 🎲 💚 ✔️ 👜 🈚 🔁 👆 🈸 **🔢 🦲**, ↩️ 👈 ☝, 🎏 🈸 ⏮️ Uvicorn & 🐍 ⏪ 💥, 📤 🕳 🎏 📟 🎏 📱 👈 💪 🕳 🔃 ⚫️. @@ -238,10 +241,13 @@ * **☁ 🐕‍🦺** 👈 🍵 👉 👆 * ☁ 🐕‍🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕‍🦺 🔜 🈚 🔁 ⚫️. -!!! tip - 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. +/// tip + +🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. + +👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. - 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// ## ⏮️ 🔁 ⏭ ▶️ @@ -257,10 +263,13 @@ ↗️, 📤 💼 🌐❔ 📤 🙅‍♂ ⚠ 🏃 ⏮️ 🔁 💗 🕰, 👈 💼, ⚫️ 📚 ⏩ 🍵. -!!! tip - , ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. +/// tip - 👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 +, ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. + +👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 + +/// ### 🖼 ⏮️ 🔁 🎛 @@ -272,8 +281,11 @@ * 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸 * 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️. -!!! tip - 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// tip + +👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +/// ## ℹ 🛠️ diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index 091eb3bab..6540761ac 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -4,8 +4,11 @@ ⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂‍♂**, **🔬**, **🦁**, & 🎏. -!!! tip - 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). +/// tip + +🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). + +///
📁 🎮 👶 @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - 📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. +/// info + +📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. - 👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 +👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 + +/// ### ✍ **FastAPI** 📟 @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ↩️ 📋 🔜 ▶️ `/code` & 🔘 ⚫️ 📁 `./app` ⏮️ 👆 📟, **Uvicorn** 🔜 💪 👀 & **🗄** `app` ⚪️➡️ `app.main`. -!!! tip - 📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 +/// tip + +📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 + +/// 👆 🔜 🔜 ✔️ 📁 📊 💖: @@ -293,10 +302,13 @@ $ docker build -t myimage . -!!! tip - 👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. +/// tip + +👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. + +👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). - 👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). +/// ### ▶️ ☁ 📦 @@ -394,8 +406,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ Traefik, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**. -!!! tip - Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. +/// tip + +Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. + +/// 👐, 🇺🇸🔍 💪 🍵 ☁ 🐕‍🦺 1️⃣ 👫 🐕‍🦺 (⏪ 🏃 🈸 📦). @@ -423,8 +438,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 👉 🦲 🔜 ✊ **📐** 📨 & 📎 👈 👪 👨‍🏭 (🤞) **⚖** 🌌, ⚫️ 🛎 🤙 **📐 ⚙**. -!!! tip - 🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. +/// tip + +🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. + +/// & 🕐❔ 👷 ⏮️ 📦, 🎏 ⚙️ 👆 ⚙️ ▶️ & 🛠️ 👫 🔜 ⏪ ✔️ 🔗 🧰 📶 **🕸 📻** (✅ 🇺🇸🔍 📨) ⚪️➡️ 👈 **📐 ⚙** (👈 💪 **🤝 ❎ 🗳**) 📦(Ⓜ) ⏮️ 👆 📱. @@ -503,8 +521,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨‍🏭 📦. -!!! info - 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦. +/// info + +🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦. + +/// 🚥 👆 ⚙️ 💼 📤 🙅‍♂ ⚠ 🏃‍♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️. @@ -520,8 +541,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * tiangolo/uvicorn-🐁-fastapi. -!!! warning - 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). +/// warning + +📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). + +/// 👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨‍🏭 🛠️** ⚓️ 🔛 💽 🐚 💪. @@ -529,8 +553,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 🐕‍🦺 🏃 **⏮️ 🔁 ⏭ ▶️** ⏮️ ✍. -!!! tip - 👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi. +/// tip + +👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi. + +/// ### 🔢 🛠️ 🔛 🛂 ☁ 🖼 @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 1️⃣1️⃣. 🏃 `uvicorn` 📋, 💬 ⚫️ ⚙️ `app` 🎚 🗄 ⚪️➡️ `app.main`. -!!! tip - 🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. +/// tip + +🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. + +/// **☁ ▶️** 🍕 `Dockerfile` 👈 👷 **🍕 📦 🖼** 👈 🕴 ⚙️ 🏗 📁 ⚙️ ⏪. diff --git a/docs/em/docs/deployment/https.md b/docs/em/docs/deployment/https.md index 3feb3a2c2..31cf99001 100644 --- a/docs/em/docs/deployment/https.md +++ b/docs/em/docs/deployment/https.md @@ -4,8 +4,11 @@ ✋️ ⚫️ 🌌 🌖 🏗 🌘 👈. -!!! tip - 🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩‍🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. +/// tip + +🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩‍🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. + +/// **💡 🔰 🇺🇸🔍**, ⚪️➡️ 🏬 🤔, ✅ https://howhttps.works/. @@ -68,8 +71,11 @@ 👆 🔜 🎲 👉 🕐, 🥇 🕰, 🕐❔ ⚒ 🌐 🆙. -!!! tip - 👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. +/// tip + +👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. + +/// ### 🏓 @@ -115,8 +121,11 @@ & 👈 ⚫️❔ **🇺🇸🔍** , ⚫️ ✅ **🇺🇸🔍** 🔘 **🔐 🤝 🔗** ↩️ 😁 (💽) 🕸 🔗. -!!! tip - 👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. +/// tip + +👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. + +/// ### 🇺🇸🔍 📨 diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md index 43cbc9409..8ebe00c7c 100644 --- a/docs/em/docs/deployment/manually.md +++ b/docs/em/docs/deployment/manually.md @@ -22,75 +22,89 @@ 👆 💪 ❎ 🔫 🔗 💽 ⏮️: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. +* Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip -
+❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. - !!! tip - ❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. +👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. - 👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. +/// -=== "Hypercorn" +//// - * Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. +//// tab | Hypercorn -
+* Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+...⚖️ 🙆 🎏 🔫 💽. - ...⚖️ 🙆 🎏 🔫 💽. +//// ## 🏃 💽 📋 👆 💪 ⤴️ 🏃 👆 🈸 🎏 🌌 👆 ✔️ ⌛ 🔰, ✋️ 🍵 `--reload` 🎛, ✅: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. -!!! warning - 💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. + `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. - `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. +⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. - ⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. +/// ## Hypercorn ⏮️ 🎻 diff --git a/docs/em/docs/deployment/server-workers.md b/docs/em/docs/deployment/server-workers.md index 43998bc49..eb29b2376 100644 --- a/docs/em/docs/deployment/server-workers.md +++ b/docs/em/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ 📥 👤 🔜 🎦 👆 ❔ ⚙️ **🐁** ⏮️ **Uvicorn 👨‍🏭 🛠️**. -!!! info - 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. +/// info - 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. +🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. + +/// ## 🐁 ⏮️ Uvicorn 👨‍🏭 diff --git a/docs/em/docs/deployment/versions.md b/docs/em/docs/deployment/versions.md index 8bfdf9731..6c9b8f9bb 100644 --- a/docs/em/docs/deployment/versions.md +++ b/docs/em/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI ⏩ 🏛 👈 🙆 "🐛" ⏬ 🔀 🐛 🔧 & 🚫-💔 🔀. -!!! tip - "🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. +/// tip + +"🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. + +/// , 👆 🔜 💪 📌 ⏬ 💖: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 💔 🔀 & 🆕 ⚒ 🚮 "🇺🇲" ⏬. -!!! tip - "🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. +/// tip + +"🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. + +/// ## ♻ FastAPI ⏬ diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md index 08db2d4c1..486b134d4 100644 --- a/docs/em/docs/external-links.md +++ b/docs/em/docs/external-links.md @@ -6,8 +6,11 @@ 📥 ❌ 📇 👫. -!!! tip - 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ 🚲 📨 ❎ ⚫️. +/// tip + +🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ 🚲 📨 ❎ ⚫️. + +/// ## 📄 diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 3693f4c54..13cafa72f 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` ⛓: +/// info - 🚶‍♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` ⛓: + +🚶‍♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 👨‍🎨 🐕‍🦺 diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index 4a285062d..099485222 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -170,12 +170,15 @@ * ⤴️ **🏤** 💬 👈 👆 👈, 👈 ❔ 👤 🔜 💭 👆 🤙 ✅ ⚫️. -!!! info - 👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. +/// info - 📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 +👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. - , ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 +📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 + +, ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 + +/// * 🚥 🇵🇷 💪 📉 🌌, 👆 💪 💭 👈, ✋️ 📤 🙅‍♂ 💪 💁‍♂️ 😟, 📤 5️⃣📆 📚 🤔 ☝ 🎑 (& 👤 🔜 ✔️ 👇 👍 👍 👶), ⚫️ 👻 🚥 👆 💪 🎯 🔛 ⚛ 👜. @@ -226,10 +229,13 @@ 🛑 👶 😧 💬 💽 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪. -!!! tip - ❔, 💭 👫 📂 💬, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. +/// tip + +❔, 💭 👫 📂 💬, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. + +⚙️ 💬 🕴 🎏 🏢 💬. - ⚙️ 💬 🕴 🎏 🏢 💬. +/// ### 🚫 ⚙️ 💬 ❔ diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 2d33d4feb..1f66c6eda 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ 🖼, 🚥 👆 💚 ✍ ⚖️ 🔬 📨 💪 ⏭ ⚫️ 🛠️ 👆 🈸. -!!! danger - 👉 "🏧" ⚒. +/// danger - 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. +👉 "🏧" ⚒. + +🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. + +/// ## ⚙️ 💼 @@ -27,8 +30,11 @@ ### ✍ 🛃 `GzipRequest` 🎓 -!!! tip - 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕‍🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕‍🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// 🥇, 👥 ✍ `GzipRequest` 🎓, ❔ 🔜 📁 `Request.body()` 👩‍🔬 🗜 💪 🔍 ☑ 🎚. @@ -54,16 +60,19 @@ {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "📡 ℹ" - `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. +/// note | "📡 ℹ" - `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. +`Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. - `scope` `dict` & `receive` 🔢 👯‍♂️ 🍕 🔫 🔧. + `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. - & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + `scope` `dict` & `receive` 🔢 👯‍♂️ 🍕 🔫 🔧. - 💡 🌅 🔃 `Request` ✅ 💃 🩺 🔃 📨. + & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + +💡 🌅 🔃 `Request` ✅ 💃 🩺 🔃 📨. + +/// 🕴 👜 🔢 📨 `GzipRequest.get_route_handler` 🔨 🎏 🗜 `Request` `GzipRequest`. @@ -75,10 +84,13 @@ ## 🔐 📨 💪 ⚠ 🐕‍🦺 -!!! tip - ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕‍🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). +/// tip + +❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕‍🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). + +✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. - ✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. +/// 👥 💪 ⚙️ 👉 🎏 🎯 🔐 📨 💪 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 6b3bc0075..dc9adf80e 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -1,11 +1,14 @@ # ↔ 🗄 -!!! warning - 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. +/// warning - 🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. +👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. - 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. +🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. + +🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. + +/// 📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗. diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 686a77949..b8610b767 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -4,12 +4,15 @@ 👆 💪 🌀 😐 FastAPI *➡ 🛠️* ⏮️ 🕹 🔛 🎏 🈸. -!!! tip - **🕹** ❎ 📶 🎯 ⚙️ 💼. +/// tip - ⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. +**🕹** ❎ 📶 🎯 ⚙️ 💼. - ⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 +⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. + +⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 + +/// ## 🕹 🗃 @@ -46,8 +49,11 @@ ⚫️ 😢 ⚪️➡️ 💃, ✋️ 🚥 👆 ✔️ 📟 👈 ⚙️ ⚫️, 👆 💪 💪 **↔** 💃-Graphene3️⃣, 👈 📔 🎏 ⚙️ 💼 & ✔️ **🌖 🌓 🔢**. -!!! tip - 🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 🍓, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. +/// tip + +🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 🍓, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. + +/// ## 💡 🌅 diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md index 8d633d7f6..88b827c24 100644 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ b/docs/em/docs/how-to/sql-databases-peewee.md @@ -1,16 +1,22 @@ # 🗄 (🔗) 💽 ⏮️ 🏒 -!!! warning - 🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. +/// warning - 💭 🆓 🚶 👉. +🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. + +💭 🆓 🚶 👉. + +/// 🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜. 🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ 🏒 🐜, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**. -!!! warning "🐍 3️⃣.7️⃣ ➕ ✔" - 👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. +/// warning | "🐍 3️⃣.7️⃣ ➕ ✔" + +👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. + +/// ## 🏒 🔁 @@ -24,8 +30,11 @@ 👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI. -!!! note "📡 ℹ" - 👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, , 🇵🇷. +/// note | "📡 ℹ" + +👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, , 🇵🇷. + +/// ## 🎏 📱 @@ -65,8 +74,11 @@ {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - ✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. +/// tip + +✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. + +/// #### 🗒 @@ -84,9 +96,11 @@ connect_args={"check_same_thread": False} ...⚫️ 💪 🕴 `SQLite`. -!!! info "📡 ℹ" +/// info | "📡 ℹ" - ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. +⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. + +/// ### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` @@ -94,14 +108,17 @@ connect_args={"check_same_thread": False} & `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍. -!!! note "📡 ℹ" - `threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. +/// note | "📡 ℹ" + +`threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. - 👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅‍♂ 🌖, 🙅‍♂ 🌘. +👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅‍♂ 🌖, 🙅‍♂ 🌘. - ⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. +⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. - ✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. +✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. + +/// ✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒. @@ -125,10 +142,13 @@ connect_args={"check_same_thread": False} , 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI. -!!! tip - 👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. +/// tip + +👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. - ✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. +✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. + +/// ### ⚙️ 🛃 `PeeweeConnectionState` 🎓 @@ -138,11 +158,17 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - ⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. +/// tip + +⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. + +/// + +/// tip -!!! tip - 👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. +👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. + +/// ## ✍ 💽 🏷 @@ -154,10 +180,13 @@ connect_args={"check_same_thread": False} 👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰. -!!! tip - 🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. +/// tip + +🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. +✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. + +/// 🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. @@ -165,25 +194,31 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` -!!! tip - 🏒 ✍ 📚 🎱 🔢. +/// tip + +🏒 ✍ 📚 🎱 🔢. - ⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. +⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. - ⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. +⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. - `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. + `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. + +/// ## ✍ Pydantic 🏷 🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. -!!! tip - ❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. +/// tip + +❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). +👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. +👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. + +/// ### ✍ Pydantic *🏷* / 🔗 @@ -193,12 +228,15 @@ connect_args={"check_same_thread": False} {!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` -!!! tip - 📥 👥 🏗 🏷 ⏮️ `id`. +/// tip + +📥 👥 🏗 🏷 ⏮️ `id`. - 👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. +👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. - 👥 ❎ 🎱 `owner_id` 🔢 `Item`. +👥 ❎ 🎱 `owner_id` 🔢 `Item`. + +/// ### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗 @@ -224,8 +262,11 @@ connect_args={"check_same_thread": False} & ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`. -!!! tip - 👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. +/// tip + +👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. + +/// ## 💩 🇨🇻 @@ -297,12 +338,15 @@ list(models.User.select()) **⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). -!!! tip - FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. +/// tip + +FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. - ✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. +✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. - & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. + & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. + +/// #### 🏒 🗳 @@ -467,8 +511,11 @@ async def reset_db_state(): ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. +/// warning + +👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. + +/// ### ⚠ diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index b3026917a..202c90f94 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -12,8 +12,11 @@ ✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫. -!!! note - 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. +/// note + +🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. + +/// ## 🎯 @@ -164,45 +167,55 @@ John Doe 🖼, ➡️ 🔬 🔢 `list` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): +⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. - 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 🆎, 🚮 `list`. +🆎, 🚮 `list`. - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -!!! info - 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". +//// - 👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). +/// info + +👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". + +👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). + +/// 👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`". -!!! tip - 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. +/// tip + +🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. + +/// 🔨 👈, 👆 👨‍🎨 💪 🚚 🐕‍🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇: @@ -218,17 +231,21 @@ John Doe 👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// 👉 ⛓: @@ -243,17 +260,21 @@ John Doe 🥈 🆎 🔢 💲 `dict`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// 👉 ⛓: @@ -269,17 +290,21 @@ John Doe 🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// 👯‍♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`. @@ -299,23 +324,29 @@ John Doe 👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### ⚙️ `Union` ⚖️ `Optional` @@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉 👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...& 🎏. - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...& 🎏. +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - * `Union` - * `Optional` - * ...& 🎏. +* `Union` +* `Optional` +* ...& 🎏. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - * `list` - * `tuple` - * `set` - * `dict` +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: +* `list` +* `tuple` +* `set` +* `dict` - * `Union` - * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) - * ...& 🎏. + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. +* `Union` +* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) +* ...& 🎏. + +🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. + +//// ### 🎓 🆎 @@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉 🖼 ⚪️➡️ 🛂 Pydantic 🩺: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. +💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. + +/// **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩‍💻 🦮](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. +/// tip + +Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. + +/// ## 🆎 🔑 **FastAPI** @@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉 ⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨‍🎨, ♒️), **FastAPI** 🔜 📚 👷 👆. -!!! info - 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. +/// info + +🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. + +/// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index e28ead415..1d17a0e4e 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index fc9076aa8..693a75d28 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪. -!!! info - 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. +/// info + +🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. + +/// ## 🖼 📁 📊 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. +/// tip + +📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. - 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. +👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. - 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: +🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`. * ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`. @@ -99,8 +105,11 @@ 🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️. -!!! tip - 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. +/// tip + +👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. + +/// 👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`. @@ -116,10 +125,13 @@ {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 👥 ⚙️ 💭 🎚 📉 👉 🖼. +/// tip + +👥 ⚙️ 💭 🎚 📉 👉 🖼. + +✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](security/index.md){.internal-link target=_blank}. - ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](security/index.md){.internal-link target=_blank}. +/// ## ➕1️⃣ 🕹 ⏮️ `APIRouter` @@ -163,8 +175,11 @@ async def read_item(item_id: str): & 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫. -!!! tip - 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. +/// tip + +🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. + +/// 🔚 🏁 👈 🏬 ➡ 🔜: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨‍🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗. * 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. +/// tip + +✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. + +/// + +/// check -!!! check - `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. +`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. + +/// ### 🗄 🔗 @@ -201,8 +222,11 @@ async def read_item(item_id: str): #### ❔ ⚖ 🗄 👷 -!!! tip - 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. +/// tip + +🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. + +/// 👁 ❣ `.`, 💖: @@ -269,10 +293,13 @@ that 🔜 ⛓: {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. +/// tip + +👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. - & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + +/// ## 👑 `FastAPI` @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 🥇 ⏬ "⚖ 🗄": +/// info + +🥇 ⏬ "⚖ 🗄": - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 🥈 ⏬ "🎆 🗄": +🥈 ⏬ "🎆 🗄": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. - 💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. +/// ### ❎ 📛 💥 @@ -372,26 +402,35 @@ from .routers.users import router {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. +/// info - & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. +`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. + + & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. + +/// ⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸. ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -!!! note "📡 ℹ" - ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. +/// note | "📡 ℹ" + +⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. + +, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. + +/// - , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. +/// check -!!! check - 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. +👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. - 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. +👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. - ⚫️ 🏆 🚫 📉 🎭. 👶 +⚫️ 🏆 🚫 📉 🎭. 👶 + +/// ### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies` @@ -438,16 +477,19 @@ from .routers.users import router & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -!!! info "📶 📡 ℹ" - **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. +/// info | "📶 📡 ℹ" + +**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. + +--- - --- + `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. - `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. +👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. - 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. +👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. - 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. +/// ## ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index 9f2c914f4..c5a04daeb 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -!!! warning - 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +/// warning + +👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). + +/// ## 📣 🏷 🔢 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -!!! note "📡 ℹ" - 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. +/// note | "📡 ℹ" - & Pydantic `Field` 📨 👐 `FieldInfo` 👍. +🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. - `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. + & Pydantic `Field` 📨 👐 `FieldInfo` 👍. - 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. -!!! tip - 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. +💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// + +/// tip + +👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. + +/// ## 🚮 ➕ ℹ @@ -57,9 +74,12 @@ 👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼. -!!! warning - ➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. - 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. +/// warning + +➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. +👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. + +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 9ada7dee1..c2a9a224d 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +//// -!!! note - 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. +/// note + +👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. + +/// ## 💗 💪 🔢 @@ -38,17 +45,21 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -69,9 +80,11 @@ } ``` -!!! note - 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. +/// note +👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. + +/// **FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`. @@ -87,17 +100,21 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -137,20 +154,27 @@ q: str | None = None 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +```Python hl_lines="26" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. -!!! info - `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. +/// ## ⏯ 👁 💪 🔢 @@ -166,17 +190,21 @@ item: Item = Body(embed=True) : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index c941fa08a..23114540a 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +//// 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -61,23 +65,29 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +//// ## ⚒ 🆎 @@ -87,23 +97,29 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -125,45 +141,57 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -196,23 +224,29 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` + +//// 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -220,23 +254,29 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info - 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. +/// info + +👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. + +/// ## 🙇 🐦 🏷 👆 💪 🔬 🎲 🙇 🐦 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` + +//// - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ -!!! info - 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ +/// ## 💪 😁 📇 @@ -308,17 +360,21 @@ images: list[Image] : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` + +//// ## 👨‍🎨 🐕‍🦺 🌐 @@ -348,26 +404,33 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. -!!! tip - ✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. +✋️ Pydantic ✔️ 🏧 💽 🛠️. - ✋️ Pydantic ✔️ 🏧 💽 🛠️. +👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. - 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. + & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. - & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 89bb615f6..97501eb6d 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +//// `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -48,14 +54,17 @@ 👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣. -!!! note - `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. +/// note + +`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. + + & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. - & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. +👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. - 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. +✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. - ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. +/// ### ⚙️ Pydantic `exclude_unset` 🔢 @@ -67,23 +76,29 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// ### ⚙️ Pydantic `update` 🔢 @@ -91,23 +106,29 @@ 💖 `stored_item_model.copy(update=update_data)`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// ### 🍕 ℹ 🌃 @@ -124,32 +145,44 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +/// -!!! tip - 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. +/// note - ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. +👀 👈 🔢 🏷 ✔. -!!! note - 👀 👈 🔢 🏷 ✔. +, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). - , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). +🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. - 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 12f5a6315..79d8e716f 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -8,28 +8,35 @@ 📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. -!!! info - 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. +/// info - 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. +📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. - ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. +📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. + +⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. + +/// ## 🗄 Pydantic `BaseModel` 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## ✍ 👆 💽 🏷 @@ -37,17 +44,21 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -75,17 +86,21 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -134,32 +149,39 @@ -!!! tip - 🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. +/// tip + +🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. - ⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: +⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: - * 🚘-🛠️ - * 🆎 ✅ - * 🛠️ - * 🔎 - * 🔬 +* 🚘-🛠️ +* 🆎 ✅ +* 🛠️ +* 🔎 +* 🔬 + +/// ## ⚙️ 🏷 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## 📨 💪 ➕ ➡ 🔢 @@ -167,17 +189,21 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -185,17 +211,21 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// 🔢 🔢 🔜 🤔 ⏩: @@ -203,10 +233,13 @@ * 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢. * 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. + + `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. - `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. +/// ## 🍵 Pydantic diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 47f4a62f5..891999028 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Cookie`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// ## 📣 `Cookie` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +/// note | "📡 ℹ" - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 8c5e33ed7..690b8973a 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -78,7 +78,10 @@ 🌖 ℹ 🔃 , ✅ 🦎 ⚜ 🧾. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. +/// note | "📡 ℹ" - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index c7c11b5ce..abef2a50c 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app 🔜 🚫 🛠️. -!!! info - 🌅 ℹ, ✅ 🛂 🐍 🩺. +/// info + +🌅 ℹ, ✅ 🛂 🐍 🩺. + +/// ## 🏃 👆 📟 ⏮️ 👆 🕹 diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index e2d2686d3..f14239b0f 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ...: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...& **FastAPI** 🔜 💭 ⚫️❔. -!!! tip - 🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. +/// tip + +🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. + +⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. - ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. +/// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4d54b91c7..bf267e056 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,17 +20,23 @@ 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. -!!! tip - 👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. +/// tip - ⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. +👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. - ⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. +⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. -!!! info - 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. +⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. - ✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. +/// + +/// info + +👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. + +✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. + +/// ## 🔗 ❌ & 📨 💲 diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 3ed5aeba5..5998d06df 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI 🐕‍🦺 🔗 👈 🏗 🎓 ⏮️ 2️⃣ 👩‍🔬: `__enter__()` & `__exit__()`. @@ -204,16 +228,19 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - ➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: +/// tip + +➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: + +* `@contextlib.contextmanager` ⚖️ +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` ⚖️ - * `@contextlib.asynccontextmanager` +⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. - ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. +👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. - 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. +✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). - ✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). +FastAPI 🔜 ⚫️ 👆 🔘. - FastAPI 🔜 ⚫️ 👆 🔘. +/// diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md index ffd38d716..efb4ee672 100644 --- a/docs/em/docs/tutorial/dependencies/index.md +++ b/docs/em/docs/tutorial/dependencies/index.md @@ -31,17 +31,21 @@ ⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// 👈 ⚫️. @@ -63,33 +67,41 @@ ### 🗄 `Depends` -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. @@ -99,8 +111,11 @@ & 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* . -!!! tip - 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. +/// tip + +👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. + +/// 🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅: @@ -121,10 +136,13 @@ common_parameters --> read_users 👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*. -!!! check - 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. +/// check - 👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. +👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. + +👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. + +/// ## `async` ⚖️ 🚫 `async` @@ -136,8 +154,11 @@ common_parameters --> read_users ⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔. -!!! note - 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. +/// note + +🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. + +/// ## 🛠️ ⏮️ 🗄 diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 454ff5129..02b33ccd7 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,17 +10,21 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -30,17 +34,21 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ➡️ 🎯 🔛 🔢 📣: @@ -53,22 +61,29 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. -!!! info - 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. +✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. - ✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. +/// ```mermaid graph TB @@ -102,9 +117,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False ✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲). -!!! tip - 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. +/// tip + +🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. + +✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. - ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. + & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. - & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. +/// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 75ca3824d..314f5b324 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` + +//// 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. @@ -38,5 +42,8 @@ ⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻. -!!! note - `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. +/// note + +`jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. + +/// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 54a186f12..cbe111079 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 82f974d9f..4703c7123 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **🔢 🏷** 🔜 🚫 ✔️ 🔐. * **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐. -!!! danger - 🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. +/// danger - 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. +🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. + +🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. + +/// ## 💗 🏷 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// ### 🔃 `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning - 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. +/// warning + +🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. + +/// ## 📉 ❎ @@ -158,17 +168,21 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// ## `Union` ⚖️ `anyOf` @@ -178,20 +192,27 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 `typing.Union`: -!!! note - 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. +/// note + +🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.6️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// ## 📨 ⏮️ ❌ `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` + +//// - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index b8d3f6b56..158189e6e 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note - 📋 `uvicorn main:app` 🔗: +/// note - * `main`: 📁 `main.py` (🐍 "🕹"). - * `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. - * `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. +📋 `uvicorn main:app` 🔗: + +* `main`: 📁 `main.py` (🐍 "🕹"). +* `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. +* `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. + +/// 🔢, 📤 ⏸ ⏮️ 🕳 💖: @@ -136,10 +139,13 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -!!! note "📡 ℹ" - `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. +/// note | "📡 ℹ" + +`FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. - 👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. +👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. + +/// ### 🔁 2️⃣: ✍ `FastAPI` "👐" @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "➡" 🛎 🤙 "🔗" ⚖️ "🛣". +/// info + +"➡" 🛎 🤙 "🔗" ⚖️ "🛣". + +/// ⏪ 🏗 🛠️, "➡" 👑 🌌 🎏 "⚠" & "ℹ". @@ -250,16 +259,19 @@ https://example.com/items/foo * ➡ `/` * ⚙️ get 🛠️ -!!! info "`@decorator` ℹ" - 👈 `@something` ❕ 🐍 🤙 "👨‍🎨". +/// info | "`@decorator` ℹ" - 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). +👈 `@something` ❕ 🐍 🤙 "👨‍🎨". - "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. +👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). - 👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. - ⚫️ "**➡ 🛠️ 👨‍🎨**". +👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + +⚫️ "**➡ 🛠️ 👨‍🎨**". + +/// 👆 💪 ⚙️ 🎏 🛠️: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. +/// tip + +👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. - **FastAPI** 🚫 🛠️ 🙆 🎯 🔑. +**FastAPI** 🚫 🛠️ 🙆 🎯 🔑. - ℹ 📥 🎁 📄, 🚫 📄. +ℹ 📥 🎁 📄, 🚫 📄. - 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. +🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. + +/// ### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢** @@ -309,8 +324,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. +/// note + +🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. + +/// ### 🔁 5️⃣: 📨 🎚 diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index 36d58e2af..ed32ab53a 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ } ``` -!!! tip - 🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. +/// tip - 👆 💪 🚶‍♀️ `dict`, `list`, ♒️. +🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. - 👫 🍵 🔁 **FastAPI** & 🗜 🎻. +👆 💪 🚶‍♀️ `dict`, `list`, ♒️. + +👫 🍵 🔁 **FastAPI** & 🗜 🎻. + +/// ## 🚮 🛃 🎚 @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. +/// ## 🔐 🔢 ⚠ 🐕‍🦺 @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` 🆚 `ValidationError` -!!! warning - 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. +/// warning + +👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. + +/// `RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### ⚙️ `RequestValidationError` 💪 diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 0f33a1774..82583c7c3 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Header`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// ## 📣 `Header` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +/// note | "📡 ℹ" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🏧 🛠️ @@ -60,20 +74,27 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// warning - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. -!!! warning - ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. +/// ## ❎ 🎚 @@ -85,23 +106,29 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md index fd6900db0..5f7532341 100644 --- a/docs/em/docs/tutorial/index.md +++ b/docs/em/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟. -!!! note - 👆 💪 ❎ ⚫️ 🍕 🍕. +/// note - 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: +👆 💪 ❎ ⚫️ 🍕 🍕. - ``` - pip install "fastapi[standard]" - ``` +👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: - ❎ `uvicorn` 👷 💽: +``` +pip install "fastapi[standard]" +``` + +❎ `uvicorn` 👷 💽: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` + & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. - & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. +/// ## 🏧 👩‍💻 🦮 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 97d345fa2..6caeed4cd 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -21,8 +21,11 @@ {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip - 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. +/// tip + +👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. + +/// ⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖: @@ -54,8 +57,11 @@ 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). -!!! tip - 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. +/// tip + +👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. + +/// ### ⚙️ 👆 🔖 @@ -65,8 +71,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. +/// info + +✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### ✅ 🩺 diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index 644b4690c..b9bb12e00 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -!!! note "📡 ℹ" - 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. +/// note | "📡 ℹ" - 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. +🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. + +🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. + +/// ## ✍ 🛠️ @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. +/// tip + +✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. + +✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. + +/// + +/// note | "📡 ℹ" - ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. +👆 💪 ⚙️ `from starlette.requests import Request`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +**FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ### ⏭ & ⏮️ `response` diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 916529258..1979bed2b 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ 📤 📚 🔢 👈 👆 💪 🚶‍♀️ 👆 *➡ 🛠️ 👨‍🎨* 🔗 ⚫️. -!!! warning - 👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. +/// warning + +👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. + +/// ## 📨 👔 📟 @@ -13,52 +16,67 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔖 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -80,23 +98,29 @@ 👆 💪 🚮 `summary` & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## 📛 ⚪️➡️ #️⃣ @@ -104,23 +128,29 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -130,31 +160,43 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info - 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. +🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. -!!! check - 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. +, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". - , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". +/// diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index b1ba2670b..a7952984c 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// ## 📣 🗃 @@ -24,24 +28,31 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -!!! note - ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. +//// - , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. +/// note - 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. +➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. + +, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. + +👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. + +/// ## ✔ 🔢 👆 💪 @@ -121,18 +132,24 @@ * `lt`: `l`👭 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -!!! info - `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. +/// info + +`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. + +🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. + +/// + +/// note | "📡 ℹ" - 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. +🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. -!!! note "📡 ℹ" - 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. +👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. - 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. +, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. - , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. +👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. - 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. +👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. - 👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. +/// diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ac64d2ebb..e0d51a1df 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ 👉 💼, `item_id` 📣 `int`. -!!! check - 👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. +/// check + +👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. + +/// ## 💽 🛠️ @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check - 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. +/// check + +👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. + +, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". - , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". +/// ## 💽 🔬 @@ -63,12 +69,15 @@ 🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2 -!!! check - , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. +/// check - 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. +, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. - 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. +👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. + +👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. + +/// ## 🧾 @@ -76,10 +85,13 @@ -!!! check - 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). +/// check + +🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). + +👀 👈 ➡ 🔢 📣 🔢. - 👀 👈 ➡ 🔢 📣 🔢. +/// ## 🐩-⚓️ 💰, 🎛 🧾 @@ -139,11 +151,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. +/// info -!!! tip - 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. +🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. + +/// + +/// tip + +🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. + +/// ### 📣 *➡ 🔢* @@ -179,8 +197,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. +/// tip + +👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. + +/// #### 📨 *🔢 👨‍🎓* @@ -233,10 +254,13 @@ {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). +/// tip + +👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). + +👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. - 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index 1268c0d6e..23873155e 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ ➡️ ✊ 👉 🈸 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +//// 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. - `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. + `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. + +/// ## 🌖 🔬 @@ -31,33 +38,41 @@ 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -87,22 +102,25 @@ q: str | None = None ✋️ ⚫️ 📣 ⚫️ 🎯 💆‍♂ 🔢 🔢. -!!! info - ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: +/// info - ```Python - = None - ``` +✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: - ⚖️: +```Python += None +``` + +⚖️: + +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. - ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. + `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. - `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. +/// ⤴️, 👥 💪 🚶‍♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻: @@ -116,33 +134,41 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -164,8 +190,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - ✔️ 🔢 💲 ⚒ 🔢 📦. +/// note + +✔️ 🔢 💲 ⚒ 🔢 📦. + +/// ## ⚒ ⚫️ ✔ @@ -201,10 +230,13 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". +/// info + +🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". + +⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. +/// 👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. @@ -214,20 +246,27 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. -!!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. +/// ### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) @@ -237,8 +276,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. +/// tip + +💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. + +/// ## 🔢 🔢 📇 / 💗 💲 @@ -246,23 +288,29 @@ q: Union[str, None] = Query(default=None, min_length=3) 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// ⤴️, ⏮️ 📛 💖: @@ -283,8 +331,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. +/// tip + +📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. + +/// 🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲: @@ -294,17 +345,21 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// 🚥 👆 🚶: @@ -331,10 +386,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. +/// note - 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. +✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. + +🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. + +/// ## 📣 🌅 🗃 @@ -342,38 +400,49 @@ http://localhost:8000/items/ 👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩‍💻 🔢 & 🔢 🧰. -!!! note - ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. +/// note + +✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. - 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. +👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. + +/// 👆 💪 🚮 `title`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` + +//// & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// ## 📛 🔢 @@ -393,17 +462,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// ## 😛 🔢 @@ -413,17 +486,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +//// 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -433,17 +510,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index 746b0af9e..9bdab9e3c 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. -!!! check - 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. +/// check + +👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. + +/// ## 🔢 🔢 🆎 🛠️ 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// 👉 💼, 🚥 👆 🚶: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` + +//// - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// ## ✔ 🔢 🔢 @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// 👉 💼, 📤 3️⃣ 🔢 🔢: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, `int` ⏮️ 🔢 💲 `0`. * `limit`, 📦 `int`. -!!! tip - 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. +/// tip + +👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index be2218f89..010aa76bf 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -2,12 +2,15 @@ 👆 💪 🔬 📁 📂 👩‍💻 ⚙️ `File`. -!!! info - 📨 📂 📁, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁, 🥇 ❎ `python-multipart`. - 👉 ↩️ 📂 📁 📨 "📨 💽". +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ 📂 📁 📨 "📨 💽". + +/// ## 🗄 `File` @@ -25,13 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info - `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. +/// info + +`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. + +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// -!!! tip - 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +/// tip + +📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// 📁 🔜 📂 "📨 💽". @@ -90,11 +99,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 📡 ℹ" - 🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. +/// note | "`async` 📡 ℹ" + +🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. -!!! note "💃 📡 ℹ" - **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. +/// + +/// note | "💃 📡 ℹ" + +**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. + +/// ## ⚫️❔ "📨 💽" @@ -102,33 +117,43 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. +/// note | "📡 ℹ" + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 📦 📁 📂 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 14" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// ## `UploadFile` ⏮️ 🌖 🗃 @@ -146,40 +171,51 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + +/// ### 💗 📁 📂 ⏮️ 🌖 🗃 & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 0415dbf01..ab39d1b94 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. -!!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `File` & `Form` @@ -25,10 +28,13 @@ & 👆 💪 📣 📁 `bytes` & `UploadFile`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +/// warning + +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. + +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index f12d6e650..74117c47d 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. -!!! info - ⚙️ 📨, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +⚙️ 📨, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `Form` @@ -29,11 +32,17 @@ ⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️. -!!! info - `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. +/// info + +`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. + +/// + +/// tip -!!! tip - 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// ## 🔃 "📨 🏑" @@ -41,17 +50,23 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. +/// note | "📡 ℹ" + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 7103e9176..caae47d14 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +//// FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -53,35 +59,47 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` -!!! note - 👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +//// + +/// note + +👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`. FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄. -!!! tip - 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. +/// tip + +🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. + +👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. - 👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. +/// ### `response_model` 📫 @@ -95,37 +113,48 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +/// info -!!! info - ⚙️ `EmailStr`, 🥇 ❎ `email_validator`. +⚙️ `EmailStr`, 🥇 ❎ `email_validator`. - 🤶 Ⓜ. `pip install email-validator` - ⚖️ `pip install pydantic[email]`. +🤶 Ⓜ. `pip install email-validator` +⚖️ `pip install pydantic[email]`. + +/// & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -133,52 +162,67 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** ✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩‍💻 🔐 🔠 👩‍💻. -!!! danger - 🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. +/// danger + +🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. + +/// ## 🚮 🔢 🏷 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -202,17 +246,21 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` + +//// - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -278,17 +326,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -300,17 +352,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -318,23 +374,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -348,23 +410,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -377,16 +445,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 } ``` -!!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. +/// info + +FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. + +/// + +/// info -!!! info - 👆 💪 ⚙️: +👆 💪 ⚙️: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. +🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. + +/// #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 @@ -421,10 +495,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t , 👫 🔜 🔌 🎻 📨. -!!! tip - 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. +/// tip + +👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. + +👫 💪 📇 (`[]`), `float` `10.5`, ♒️. - 👫 💪 📇 (`[]`), `float` `10.5`, ♒️. +/// ### `response_model_include` & `response_model_exclude` @@ -434,45 +511,59 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢. -!!! tip - ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. +/// tip + +✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. + +👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. - 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. +👉 ✔ `response_model_by_alias` 👈 👷 ➡. - 👉 ✔ `response_model_by_alias` 👈 👷 ➡. +/// -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// tip -!!! tip - ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. +❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. - ⚫️ 🌓 `set(["name", "description"])`. +⚫️ 🌓 `set(["name", "description"])`. + +/// #### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index e5149de7d..57c44777a 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - 👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +/// note + +👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟. -!!! info - `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. +/// info + +`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. + +/// ⚫️ 🔜: @@ -27,15 +33,21 @@ -!!! note - 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. +/// note + +📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. + +FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. - FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. +/// ## 🔃 🇺🇸🔍 👔 📟 -!!! note - 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. +/// note + +🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. + +/// 🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨. @@ -54,8 +66,11 @@ * 💊 ❌ ⚪️➡️ 👩‍💻, 👆 💪 ⚙️ `400`. * `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟. -!!! tip - 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. +/// tip + +💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. + +/// ## ⌨ 💭 📛 @@ -79,10 +94,13 @@ -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔀 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index 114d5a84a..8562de09c 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` + +//// 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. -!!! tip - 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. +/// tip + +👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. + +🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. - 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. +/// ## `Field` 🌖 ❌ @@ -33,20 +40,27 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +/// warning -!!! warning - 🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. +🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. + +/// ## `example` & `examples` 🗄 @@ -66,17 +80,21 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -97,17 +115,21 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -117,10 +139,13 @@ ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. +/// warning + +👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. + +🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. - 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. +/// 🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 8c2c95cfd..538ea7b0a 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -26,12 +26,15 @@ ## 🏃 ⚫️ -!!! info - 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +🥇 ❎ `python-multipart`. - 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. + +/// 🏃 🖼 ⏮️: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload -!!! check "✔ 🔼 ❗" - 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. +/// check | "✔ 🔼 ❗" + +👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. + + & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. - & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. +/// & 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑): -!!! note - ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. +/// note + +⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. + +/// 👉 ↗️ 🚫 🕸 🏁 👩‍💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️. @@ -105,14 +114,17 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓. -!!! info - "📨" 🤝 🚫 🕴 🎛. +/// info + +"📨" 🤝 🚫 🕴 🎛. - ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. +✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. - & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. + & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. - 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. +👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. + +/// 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. @@ -120,21 +132,27 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip - 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. +/// tip + +📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. - ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. +↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. - ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// 👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩‍💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️. 👥 🔜 🔜 ✍ ☑ ➡ 🛠️. -!!! info - 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. +/// info + +🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. - 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. +👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. + +/// `oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲". @@ -158,10 +176,13 @@ oauth2_scheme(some, parameters) **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂‍♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺). -!!! info "📡 ℹ" - **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. +/// info | "📡 ℹ" + +**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. + +🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. - 🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. +/// ## ⚫️❔ ⚫️ 🔨 diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 455cb4f46..15545f427 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -16,17 +16,21 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## ✍ `get_current_user` 🔗 @@ -38,63 +42,81 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. 👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅. -!!! tip - 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. +/// tip + +👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. + +📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. - 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. +/// -!!! check - 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. +/// check - 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. +🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. + +👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. + +/// ## 🎏 🏷 @@ -128,17 +150,21 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md index d76f7203f..1a47e5510 100644 --- a/docs/em/docs/tutorial/security/index.md +++ b/docs/em/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔. Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍. -!!! tip - 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. +/// tip +📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. + +/// ## 👩‍💻 🔗 @@ -87,10 +89,13 @@ Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮ * 👉 🏧 🔍 ⚫️❔ 🔬 👩‍💻 🔗 🔧. -!!! tip - 🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. +/// tip + +🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. + +🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. - 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. +/// ## **FastAPI** 🚙 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc3c943f8..3ab8cc986 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" 📥 👥 ⚙️ 👍 1️⃣: )/⚛. -!!! tip - 👉 🔰 ⏪ ⚙️ PyJWT. +/// tip - ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. +👉 🔰 ⏪ ⚙️ PyJWT. + +✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. + +/// ## 🔐 🔁 @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" -!!! tip - ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. +/// tip + +⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. + +, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. - , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. + & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. - & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. +/// ## #️⃣ & ✔ 🔐 @@ -96,12 +102,15 @@ $ pip install "passlib[bcrypt]" ✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐. -!!! tip - 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. +/// tip - 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. +🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. - & 🔗 ⏮️ 🌐 👫 🎏 🕰. +🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. + + & 🔗 ⏮️ 🌐 👫 🎏 🕰. + +/// ✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩‍💻. @@ -109,20 +118,27 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6 47 54-55 58-59 68-74" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// note -!!! note - 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// ## 🍵 🥙 🤝 @@ -152,17 +168,21 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="5 11-13 27-29 77-85" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ## ℹ 🔗 @@ -172,17 +192,21 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="88-105" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// ## ℹ `/token` *➡ 🛠️* @@ -190,17 +214,21 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="114-129" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ### 📡 ℹ 🔃 🥙 "📄" `sub` @@ -239,8 +267,11 @@ $ openssl rand -hex 32 🆔: `johndoe` 🔐: `secret` -!!! check - 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. +/// check + +👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. + +/// @@ -261,8 +292,11 @@ $ openssl rand -hex 32 -!!! note - 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. +/// note + +👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. + +/// ## 🏧 ⚙️ ⏮️ `scopes` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index b9e3deb3c..937546be8 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. - 👈 ℹ 🛠️ 🎯. +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - Oauth2️⃣ 👫 🎻. +👈 ℹ 🛠️ 🎯. + +Oauth2️⃣ 👫 🎻. + +/// ## 📟 🤚 `username` & `password` @@ -49,17 +52,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -68,29 +75,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀. * 📦 `grant_type`. -!!! tip - Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. +/// tip + +Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. - 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. +🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. + +/// * 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼). * 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼). -!!! info - `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. - `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. +`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. - ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. +✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. - ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. +✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. + +/// ### ⚙️ 📨 💽 -!!! tip - 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. +/// tip + +👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. + +👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. - 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. +/// 🔜, 🤚 👩‍💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑. @@ -98,17 +114,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ ❌, 👥 ⚙️ ⚠ `HTTPException`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// ### ✅ 🔐 @@ -134,17 +154,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// #### 🔃 `**user_dict` @@ -162,8 +186,11 @@ UserInDB( ) ``` -!!! info - 🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. +/// info + +🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. + +/// ## 📨 🤝 @@ -175,31 +202,41 @@ UserInDB( 👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝. -!!! tip - ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. +/// tip + +⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. + +✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. + +/// + +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.6️⃣ & 🔛" +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. -!!! tip - 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. +👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. - 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. +⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. - ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. +🎂, **FastAPI** 🍵 ⚫️ 👆. - 🎂, **FastAPI** 🍵 ⚫️ 👆. +/// ## ℹ 🔗 @@ -213,32 +250,39 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="55-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. -!!! info - 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. +🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. - 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. +💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. - 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. +👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. - 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. +✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. - ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. +, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. - , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. +👈 💰 🐩... - 👈 💰 🐩... +/// ## 👀 ⚫️ 🎯 diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 5a5227352..2492c8708 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -18,13 +18,19 @@ ⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql +/// tip -!!! note - 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. +📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - **FastAPI** 🎯 📟 🤪 🕧. +/// + +/// note + +👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. + + **FastAPI** 🎯 📟 🤪 🕧. + +/// ## 🐜 @@ -58,8 +64,11 @@ 🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. -!!! tip - 📤 🌓 📄 ⚙️ 🏒 📥 🩺. +/// tip + +📤 🌓 📄 ⚙️ 🏒 📥 🩺. + +/// ## 📁 📊 @@ -124,9 +133,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). -!!! tip +/// tip - 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. +👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. + +/// ### ✍ 🇸🇲 `engine` @@ -148,15 +159,17 @@ connect_args={"check_same_thread": False} ...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. -!!! info "📡 ℹ" +/// info | "📡 ℹ" + +🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. +👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). +✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. +, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. +/// ### ✍ `SessionLocal` 🎓 @@ -192,10 +205,13 @@ connect_args={"check_same_thread": False} 👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. -!!! tip - 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. +/// tip + +🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. +✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. + +/// 🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). @@ -245,12 +261,15 @@ connect_args={"check_same_thread": False} 🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. -!!! tip - ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. +/// tip + +❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. + +👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). +👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. +/// ### ✍ ▶️ Pydantic *🏷* / 🔗 @@ -262,23 +281,29 @@ connect_args={"check_same_thread": False} ✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// #### 🇸🇲 👗 & Pydantic 👗 @@ -306,26 +331,35 @@ name: str 🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. -!!! tip - 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. +/// ### ⚙️ Pydantic `orm_mode` @@ -335,32 +369,41 @@ name: str `Config` 🎓, ⚒ 🔢 `orm_mode = True`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: -!!! tip - 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: +`orm_mode = True` - `orm_mode = True` +⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. +👉 ⚒ 📁 💲, 🚫 📣 🆎. - 👉 ⚒ 📁 💲, 🚫 📣 🆎. +/// Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). @@ -426,8 +469,11 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. +/// tip + +🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. + +/// ### ✍ 💽 @@ -444,34 +490,43 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. +/// tip - ✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. +🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. +✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. -!!! warning - 👉 🖼 🚫 🔐, 🔐 🚫#️⃣. + & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - 🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. +/// - 🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. +/// warning - 📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. +👉 🖼 🚫 🔐, 🔐 🚫#️⃣. -!!! tip - ↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: +🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - `item.dict()` +🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: +📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - `Item(**item.dict())` +/// - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: +/// tip - `Item(**item.dict(), owner_id=user_id)` +↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: + +`item.dict()` + + & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: + +`Item(**item.dict())` + + & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## 👑 **FastAPI** 📱 @@ -481,17 +536,21 @@ current_user.items 📶 🙃 🌌 ✍ 💽 🏓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// #### ⚗ 🗒 @@ -515,63 +574,81 @@ current_user.items 👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} +/// & ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. 👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info | "📡 ℹ" - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. -!!! info "📡 ℹ" - 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. +✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - ✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. +/// ### ✍ 👆 **FastAPI** *➡ 🛠️* 🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// 👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. @@ -579,15 +656,21 @@ current_user.items ⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. -!!! tip - 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. +/// tip + +👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. + +✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. + +/// + +/// tip - ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. +👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. -!!! tip - 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. +✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. +/// ### 🔃 `def` 🆚 `async def` @@ -616,11 +699,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. +/// info -!!! note "📶 📡 ℹ" - 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. +🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. + +/// + +/// note | "📶 📡 ℹ" + +🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. + +/// ## 🛠️ @@ -654,23 +743,29 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/schemas.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// * `sql_app/crud.py`: @@ -680,25 +775,31 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/main.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// ## ✅ ⚫️ 👆 💪 📁 👉 📟 & ⚙️ ⚫️. -!!! info +/// info + +👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. +/// ⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: @@ -739,24 +840,31 @@ $ uvicorn sql_app.main:app --reload 🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +/// ### 🔃 `request.state` @@ -777,10 +885,16 @@ $ uvicorn sql_app.main:app --reload * , 🔗 🔜 ✍ 🔠 📨. * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. -!!! tip - ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. +/// tip + +⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. + +/// + +/// info + +🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. -!!! info - 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. +⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. +/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 6090c5338..3305746c2 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. +/// note | "📡 ℹ" - **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. + +**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. + +/// ### ⚫️❔ "🗜" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 3ae51e298..75dd2d295 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## ⚙️ `TestClient` -!!! info - ⚙️ `TestClient`, 🥇 ❎ `httpx`. +/// info - 🤶 Ⓜ. `pip install httpx`. +⚙️ `TestClient`, 🥇 ❎ `httpx`. + +🤶 Ⓜ. `pip install httpx`. + +/// 🗄 `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip - 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. +/// tip + +👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. + + & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. + +👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. + +/// + +/// note | "📡 ℹ" + +👆 💪 ⚙️ `from starlette.testclient import TestClient`. - & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. +**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. +/// -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.testclient import TestClient`. +/// tip - **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. -!!! tip - 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. +/// ## 🎏 💯 @@ -110,17 +122,21 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// ### ↔ 🔬 📁 @@ -144,10 +160,13 @@ 🌖 ℹ 🔃 ❔ 🚶‍♀️ 💽 👩‍💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾. -!!! info - 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. +/// info + +🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. + +🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. - 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. +/// ## 🏃 ⚫️ diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 88d27018c..95ca90f6b 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Additional Responses in OpenAPI -!!! warning - This is a rather advanced topic. +/// warning - If you are starting with **FastAPI**, you might not need this. +This is a rather advanced topic. + +If you are starting with **FastAPI**, you might not need this. + +/// You can declare additional responses, with additional status codes, media types, descriptions, etc. @@ -27,20 +30,26 @@ For example, to declare another response with a status code `404` and a Pydantic {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note - Keep in mind that you have to return the `JSONResponse` directly. +/// note + +Keep in mind that you have to return the `JSONResponse` directly. + +/// + +/// info -!!! info - The `model` key is not part of OpenAPI. +The `model` key is not part of OpenAPI. - **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +**FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. - The correct place is: +The correct place is: - * In the key `content`, that has as value another JSON object (`dict`) that contains: - * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: - * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. - * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. +* In the key `content`, that has as value another JSON object (`dict`) that contains: + * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: + * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. + * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. + +/// The generated responses in the OpenAPI for this *path operation* will be: @@ -172,13 +181,19 @@ For example, you can add an additional media type of `image/png`, declaring that {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note - Notice that you have to return the image using a `FileResponse` directly. +/// note + +Notice that you have to return the image using a `FileResponse` directly. + +/// + +/// info + +Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). -!!! info - Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). +But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. - But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. +/// ## Combining information diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 0ce275343..99ad72b53 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ But you also want it to accept new items. And when the items didn't exist before To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - When you return a `Response` directly, like in the example above, it will be returned directly. +/// - It won't be serialized with a model, etc. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). +//// -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +//// tab | Python 3.8+ non-Annotated - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning + +When you return a `Response` directly, like in the example above, it will be returned directly. + +It won't be serialized with a model, etc. + +Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). + +/// + +/// note | "Technical Details" + +You could also use `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. + +/// ## OpenAPI and API docs diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index 0cffab56d..f65e1b180 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later. @@ -45,26 +54,35 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -72,26 +90,35 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +All this might seem contrived. And it might not be very clear how is it useful yet. -!!! tip - All this might seem contrived. And it might not be very clear how is it useful yet. +These examples are intentionally simple, but show how it all works. - These examples are intentionally simple, but show how it all works. +In the chapters about security, there are utility functions that are implemented in this same way. - In the chapters about security, there are utility functions that are implemented in this same way. +If you understood all this, you already know how those utility tools for security work underneath. - If you understood all this, you already know how those utility tools for security work underneath. +/// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index f9c82e6ab..ac459ff0c 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ The marker `@pytest.mark.anyio` tells pytest that this test function should be c {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip - Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. +/// tip + +Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. + +/// Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. @@ -81,15 +84,24 @@ response = client.get('/') ...that we used to make our requests with the `TestClient`. -!!! tip - Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +/// tip + +Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. + +/// -!!! warning - If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. +/// warning + +If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. + +/// ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. -!!! tip - If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. +/// tip + +If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. + +/// diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index c17b024f9..0447a7220 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip - The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. +/// tip + +The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. + +/// The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example: @@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -!!! note "Technical Details" - The ASGI specification defines a `root_path` for this use case. +/// note | "Technical Details" + +The ASGI specification defines a `root_path` for this use case. + +And the `--root-path` command line option provides that `root_path`. - And the `--root-path` command line option provides that `root_path`. +/// ### Checking the current `root_path` @@ -172,8 +178,11 @@ Then create a file `traefik.toml` with: This tells Traefik to listen on port 9999 and to use another file `routes.toml`. -!!! tip - We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. +/// tip + +We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. + +/// Now create that other file `routes.toml`: @@ -239,8 +248,11 @@ Now, if you go to the URL with the port for Uvicorn: http://127.0.0.1:9999/api/v1/app. @@ -283,8 +295,11 @@ This is because FastAPI uses this `root_path` to create the default `server` in ## Additional servers -!!! warning - This is a more advanced use case. Feel free to skip it. +/// warning + +This is a more advanced use case. Feel free to skip it. + +/// By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`. @@ -323,15 +338,21 @@ Will generate an OpenAPI schema like: } ``` -!!! tip - Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. +/// tip + +Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. + +/// In the docs UI at http://127.0.0.1:9999/api/v1/docs it would look like: -!!! tip - The docs UI will interact with the server that you select. +/// tip + +The docs UI will interact with the server that you select. + +/// ### Disable automatic server from `root_path` diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1d12173a1..f31127efe 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ The contents that you return from your *path operation function* will be put ins And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. -!!! note - If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. +/// note + +If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. + +/// ## Use `ORJSONResponse` @@ -31,15 +34,21 @@ But if you are certain that the content that you are returning is **serializable {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. + +In this case, the HTTP header `Content-Type` will be set to `application/json`. - In this case, the HTTP header `Content-Type` will be set to `application/json`. +And it will be documented as such in OpenAPI. - And it will be documented as such in OpenAPI. +/// -!!! tip - The `ORJSONResponse` is only available in FastAPI, not in Starlette. +/// tip + +The `ORJSONResponse` is only available in FastAPI, not in Starlette. + +/// ## HTML Response @@ -52,12 +61,15 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. - In this case, the HTTP header `Content-Type` will be set to `text/html`. +In this case, the HTTP header `Content-Type` will be set to `text/html`. - And it will be documented as such in OpenAPI. +And it will be documented as such in OpenAPI. + +/// ### Return a `Response` @@ -69,11 +81,17 @@ The same example from above, returning an `HTMLResponse`, could look like: {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning - A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. +/// warning + +A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. + +/// -!!! info - Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. +/// info + +Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. + +/// ### Document in OpenAPI and override `Response` @@ -103,10 +121,13 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import HTMLResponse`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +/// ### `Response` @@ -149,25 +170,37 @@ This is the default response used in **FastAPI**, as you read above. A fast alternative JSON response using `orjson`, as you read above. -!!! info - This requires installing `orjson` for example with `pip install orjson`. +/// info + +This requires installing `orjson` for example with `pip install orjson`. + +/// ### `UJSONResponse` An alternative JSON response using `ujson`. -!!! info - This requires installing `ujson` for example with `pip install ujson`. +/// info + +This requires installing `ujson` for example with `pip install ujson`. + +/// + +/// warning + +`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. -!!! warning - `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip - It's possible that `ORJSONResponse` might be a faster alternative. +/// tip + +It's possible that `ORJSONResponse` might be a faster alternative. + +/// ### `RedirectResponse` @@ -228,8 +261,11 @@ This includes many libraries to interact with cloud storage, video processing, a By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. -!!! tip - Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. +/// tip + +Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. + +/// ### `FileResponse` @@ -298,8 +334,11 @@ In the example below, **FastAPI** will use `ORJSONResponse` by default, in all * {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip - You can still override `response_class` in *path operations* as before. +/// tip + +You can still override `response_class` in *path operations* as before. + +/// ## Additional documentation diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 286e8f93f..252ab6fa5 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -20,12 +20,15 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. -!!! info - Keep in mind that dataclasses can't do everything Pydantic models can do. +/// info - So, you might still need to use Pydantic models. +Keep in mind that dataclasses can't do everything Pydantic models can do. - But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 +So, you might still need to use Pydantic models. + +But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 + +/// ## Dataclasses in `response_model` diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 703fcb7ae..7fd934344 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -38,10 +38,13 @@ Here we are simulating the expensive *startup* operation of loading the model by And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU. -!!! tip - The `shutdown` would happen when you are **stopping** the application. +/// tip - Maybe you need to start a new version, or you just got tired of running it. 🤷 +The `shutdown` would happen when you are **stopping** the application. + +Maybe you need to start a new version, or you just got tired of running it. 🤷 + +/// ### Lifespan function @@ -91,10 +94,13 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) -!!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. +/// warning + +The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. - You can probably skip this part. +You can probably skip this part. + +/// There's an alternative way to define this logic to be executed during *startup* and during *shutdown*. @@ -126,17 +132,23 @@ To add a function that should be run when the application is shutting down, decl Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. -!!! info - In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. +/// info + +In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. -!!! tip - Notice that in this case we are using a standard Python `open()` function that interacts with a file. +/// - So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. +/// tip - But `open()` doesn't use `async` and `await`. +Notice that in this case we are using a standard Python `open()` function that interacts with a file. - So, we declare the event handler function with standard `def` instead of `async def`. +So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. + +But `open()` doesn't use `async` and `await`. + +So, we declare the event handler function with standard `def` instead of `async def`. + +/// ### `startup` and `shutdown` together @@ -152,10 +164,13 @@ Just a technical detail for the curious nerds. 🤓 Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`. -!!! info - You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. +/// info + +You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. + +Including how to handle lifespan state that can be used in other areas of your code. - Including how to handle lifespan state that can be used in other areas of your code. +/// ## Sub Applications diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 0053ac9bb..faa7c323f 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -32,17 +32,21 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` + +//// Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -127,8 +131,11 @@ You will also get autocompletion for the payload to send: -!!! tip - Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. +/// tip + +Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. + +/// You will have inline errors for the data that you send: @@ -144,17 +151,21 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### Generate a TypeScript Client with Tags @@ -201,17 +212,21 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### Generate a TypeScript Client with Custom Operation IDs @@ -233,17 +248,21 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../../docs_src/generate_clients/tutorial004.js!} +``` - ```Javascript - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 86e42fba0..36f0720c0 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -6,10 +6,13 @@ The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_bl In the next sections you will see other options, configurations, and additional features. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 9219f1d2c..4b273fd89 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -!!! note "Technical Details" - For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. +/// note | "Technical Details" - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 1ff51f077..e74af3d3e 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -35,8 +35,11 @@ This part is pretty normal, most of the code is probably already familiar to you {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - The `callback_url` query parameter uses a Pydantic URL type. +/// tip + +The `callback_url` query parameter uses a Pydantic URL type. + +/// The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. @@ -61,10 +64,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it This example doesn't implement the callback itself (that could be just a line of code), only the documentation part. -!!! tip - The actual callback is just an HTTP request. +/// tip + +The actual callback is just an HTTP request. - When implementing the callback yourself, you could use something like HTTPX or Requests. +When implementing the callback yourself, you could use something like HTTPX or Requests. + +/// ## Write the callback documentation code @@ -74,10 +80,13 @@ But, you already know how to easily create automatic documentation for an API wi So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call). -!!! tip - When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. +/// tip + +When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. - Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. +Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. + +/// ### Create a callback `APIRouter` @@ -154,8 +163,11 @@ and it would expect a response from that *external API* with a JSON body like: } ``` -!!! tip - Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). +/// tip + +Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). + +/// ### Add the callback router @@ -167,8 +179,11 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip - Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. +/// tip + +Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. + +/// ### Check the docs diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index f7f43b357..5ee321e2a 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code. -!!! info - Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. +/// info + +Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. + +/// ## An app with webhooks @@ -35,8 +38,11 @@ When you create a **FastAPI** application, there is a `webhooks` attribute that The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. -!!! info - The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. +/// info + +The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. + +/// Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 35f7d1b8d..c8874bad9 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning - If you are not an "expert" in OpenAPI, you probably don't need this. +/// warning + +If you are not an "expert" in OpenAPI, you probably don't need this. + +/// You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`. @@ -23,13 +26,19 @@ You should do it after adding all your *path operations*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - If you manually call `app.openapi()`, you should update the `operationId`s before that. +/// tip + +If you manually call `app.openapi()`, you should update the `operationId`s before that. + +/// + +/// warning + +If you do this, you have to make sure each one of your *path operation functions* has a unique name. -!!! warning - If you do this, you have to make sure each one of your *path operation functions* has a unique name. +Even if they are in different modules (Python files). - Even if they are in different modules (Python files). +/// ## Exclude from OpenAPI @@ -65,8 +74,11 @@ There's a whole chapter here in the documentation about it, you can read it at [ When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -!!! note "Technical details" - In the OpenAPI specification it is called the Operation Object. +/// note | "Technical details" + +In the OpenAPI specification it is called the Operation Object. + +/// It has all the information about the *path operation* and is used to generate the automatic documentation. @@ -74,10 +86,13 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc. This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it. -!!! tip - This is a low level extension point. +/// tip + +This is a low level extension point. - If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. +If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`. @@ -150,20 +165,27 @@ And you could do this even if the data type in the request is not JSON. For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. -!!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. +/// Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. @@ -171,22 +193,32 @@ Then we use the request directly, and extract the body as `bytes`. This means th And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip -!!! info - In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. +Here we reuse the same Pydantic model. -!!! tip - Here we reuse the same Pydantic model. +But the same way, we could have validated it in some other way. - But the same way, we could have validated it in some other way. +/// diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index d53985dbb..85e423f42 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -30,20 +30,26 @@ Then set Cookies in it, and then return it: {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. +/// tip - So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. +Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. - And also that you are not sending any data that should have been filtered by a `response_model`. +So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. + +And also that you are not sending any data that should have been filtered by a `response_model`. + +/// ### More info -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +/// To see all the available parameters and options, check the documentation in Starlette. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8836140ec..33e10d091 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ It might be useful, for example, to return custom headers or cookies. In fact, you can return any `Response` or any sub-class of it. -!!! tip - `JSONResponse` itself is a sub-class of `Response`. +/// tip + +`JSONResponse` itself is a sub-class of `Response`. + +/// And when you return a `Response`, **FastAPI** will pass it directly. @@ -35,10 +38,13 @@ For those cases, you can use the `jsonable_encoder` to convert your data before {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ## Returning a custom `Response` diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 49b5fe476..acbb6d7e5 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -28,12 +28,15 @@ Create a response as described in [Return a Response Directly](response-directly {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | "Technical Details" - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. + +/// ## Custom Headers diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 680f4dff5..c302bf8dc 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ Then, when you type that username and password, the browser sends them in the he * It returns an object of type `HTTPBasicCredentials`: * It contains the `username` and `password` sent. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password: @@ -59,26 +68,35 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// This would be similar to: @@ -142,23 +160,32 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md index c9ede4231..edb42132e 100644 --- a/docs/en/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -4,10 +4,13 @@ There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 9a9c0dff9..69b8fa7d2 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application. -!!! warning - This is a more or less advanced section. If you are just starting, you can skip it. +/// warning - You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. +This is a more or less advanced section. If you are just starting, you can skip it. - But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. +You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. - Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. +But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. - In many cases, OAuth2 with scopes can be an overkill. +Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. - But if you know you need it, or you are curious, keep reading. +In many cases, OAuth2 with scopes can be an overkill. + +But if you know you need it, or you are curious, keep reading. + +/// ## OAuth2 scopes and OpenAPI @@ -43,63 +46,87 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. +/// info + +In OAuth2 a "scope" is just a string that declares a specific permission required. + +It doesn't matter if it has other characters like `:` or if it is a URL. - It doesn't matter if it has other characters like `:` or if it is a URL. +Those details are implementation specific. - Those details are implementation specific. +For OAuth2 they are just strings. - For OAuth2 they are just strings. +/// ## Global view First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+" +/// - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +/// -=== "Python 3.9+ non-Annotated" +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Now let's review those changes step by step. @@ -109,51 +136,71 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="64-67" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="64-67" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -171,55 +218,79 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property And we return the scopes as part of the JWT token. -!!! danger - For simplicity, here we are just adding the scopes received directly to the token. +/// danger + +For simplicity, here we are just adding the scopes received directly to the token. - But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. +But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. -=== "Python 3.10+" +/// - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.9+" +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.9+ - ```Python hl_lines="157" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Declare scopes in *path operations* and dependencies @@ -237,62 +308,89 @@ And the dependency function `get_current_active_user` can also declare sub-depen In this case, it requires the scope `me` (it could require more than one scope). -!!! note - You don't necessarily need to add different scopes in different places. +/// note + +You don't necessarily need to add different scopes in different places. + +We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 141 172" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+" +/// - ```Python hl_lines="5 140 171" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="5 140 171" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="5 141 172" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="5 140 169" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="5 140 169" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// -!!! info "Technical Details" - `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. +/// info | "Technical Details" - But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. +`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. +But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. + +But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. + +/// ## Use `SecurityScopes` @@ -308,50 +406,71 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 107" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="9 107" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="9 106" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// ## Use the `scopes` @@ -365,50 +484,71 @@ We create an `HTTPException` that we can reuse (`raise`) later at several points In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` - ```Python hl_lines="107 109-117" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="107 109-117" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Verify the `username` and data shape @@ -424,50 +564,71 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="48 118-129" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="48 118-129" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Verify the `scopes` @@ -475,50 +636,71 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="130-136" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="130-136" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// ## Dependency tree and scopes @@ -545,10 +727,13 @@ Here's how the hierarchy of dependencies and scopes looks like: * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. -!!! tip - The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. +/// tip + +The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. - All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. +All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. + +/// ## More details about `SecurityScopes` @@ -586,10 +771,13 @@ The most common is the implicit flow. The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. -!!! note - It's common that each authentication provider names their flows in a different way, to make it part of their brand. +/// note + +It's common that each authentication provider names their flows in a different way, to make it part of their brand. + +But in the end, they are implementing the same OAuth2 standard. - But in the end, they are implementing the same OAuth2 standard. +/// **FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 56af4f441..b77557361 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -8,44 +8,51 @@ For this reason it's common to provide them in environment variables that are re ## Environment Variables -!!! tip - If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. + +/// An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). You can create and use environment variables in the shell, without needing Python: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### Read env vars in Python @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - The second argument to `os.getenv()` is the default value to return. +/// tip + +The second argument to `os.getenv()` is the default value to return. - If not provided, it's `None` by default, here we provide `"World"` as the default value to use. +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// Then you could call that Python program: @@ -114,8 +124,11 @@ Hello World from Python -!!! tip - You can read more about it at The Twelve-Factor App: Config. +/// tip + +You can read more about it at The Twelve-Factor App: Config. + +/// ### Types and validation @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" -!!! info - In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. +/// info + +In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. + +/// ### Create the `Settings` object @@ -162,23 +178,33 @@ The same way as with Pydantic models, you declare class attributes with type ann You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! info - In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. +/// tip - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +If you want something quick to copy and paste, don't use this example, use the last one below. -!!! tip - If you want something quick to copy and paste, don't use this example, use the last one below. +/// Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p -!!! tip - To set multiple env vars for a single command just separate them with a space, and put them all before the command. +/// tip + +To set multiple env vars for a single command just separate them with a space, and put them all before the command. + +/// And then the `admin_email` setting would be set to `"deadpool@example.com"`. @@ -231,8 +260,11 @@ And then use it in a file `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// tip + +You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## Settings in a dependency @@ -254,54 +286,75 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// tip -!!! tip - We'll discuss the `@lru_cache` in a bit. +Prefer to use the `Annotated` version if possible. - For now you can assume `get_settings()` is a normal function. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// tip + +We'll discuss the `@lru_cache` in a bit. + +For now you can assume `get_settings()` is a normal function. + +/// And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Settings and testing @@ -321,15 +374,21 @@ If you have many settings that possibly change a lot, maybe in different environ This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv". -!!! tip - A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. +/// tip + +A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. - But a dotenv file doesn't really have to have that exact filename. +But a dotenv file doesn't really have to have that exact filename. + +/// Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. -!!! tip - For this to work, you need to `pip install python-dotenv`. +/// tip + +For this to work, you need to `pip install python-dotenv`. + +/// ### The `.env` file @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" And then update your `config.py` with: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! tip - The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. +/// tip -=== "Pydantic v1" +The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! tip - The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. +//// -!!! info - In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip + +The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. + +/// + +//// + +/// info + +In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. + +/// Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use. @@ -390,26 +462,35 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 4a577215a..43731ec36 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -31,18 +31,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. +/// note - Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. +Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. -!!! tip - By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. +Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. -!!! note "Technical Details" - You could also use `from starlette.templating import Jinja2Templates`. +/// - **FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. +/// tip + +By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. + +/// + +/// note | "Technical Details" + +You could also use `from starlette.templating import Jinja2Templates`. + +**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. + +/// ## Writing templates diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md index 1c0669b9c..974cf4caa 100644 --- a/docs/en/docs/advanced/testing-database.md +++ b/docs/en/docs/advanced/testing-database.md @@ -1,11 +1,14 @@ # Testing a Database -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + +The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + +/// You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. @@ -59,10 +62,13 @@ But the rest of the session code is more or less the same, we just copy it. {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. +/// tip + +You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - For simplicity and to focus on the specific testing code, we are just copying it. +For simplicity and to focus on the specific testing code, we are just copying it. + +/// ## Create the database @@ -88,8 +94,11 @@ Now we create the dependency override and add it to the overrides for our app. {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip - The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. +/// tip + +The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. + +/// ## Test the app diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 57dd87f56..92e25f88d 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip - You can set a dependency override for a dependency used anywhere in your **FastAPI** application. +/// tip - The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. +You can set a dependency override for a dependency used anywhere in your **FastAPI** application. - FastAPI will still be able to override it. +The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. + +FastAPI will still be able to override it. + +/// Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`: @@ -77,5 +96,8 @@ Then you can reset your overrides (remove them) by setting `app.dependency_overr app.dependency_overrides = {} ``` -!!! tip - If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). +/// tip + +If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). + +/// diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 4101e5a16..6c071bc19 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ For this, you use the `TestClient` in a `with` statement, connecting to the WebS {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note - For more details, check Starlette's documentation for testing WebSockets. +/// note + +For more details, check Starlette's documentation for testing WebSockets. + +/// diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 500afa34b..5473db5cb 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -35,18 +35,24 @@ For that you need to access the request directly. By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. -!!! tip - Note that in this case, we are declaring a path parameter beside the request parameter. +/// tip - So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. +Note that in this case, we are declaring a path parameter beside the request parameter. - The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. +So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. + +The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. + +/// ## `Request` documentation You can read more details about the `Request` object in the official Starlette documentation site. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +/// note | "Technical Details" + +You could also use `from starlette.requests import Request`. + +**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. +/// diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 3b6471dd5..9655714b0 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -50,10 +50,13 @@ In your **FastAPI** application, create a `websocket`: {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.websockets import WebSocket`. +/// note | "Technical Details" - **FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. +You could also use `from starlette.websockets import WebSocket`. + +**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. + +/// ## Await for messages and send messages @@ -112,46 +115,65 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. +As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. - You can use a closing code from the valid codes defined in the specification. +You can use a closing code from the valid codes defined in the specification. + +/// ### Try the WebSockets with dependencies @@ -174,8 +196,11 @@ There you can set: * The "Item ID", used in the path. * The "Token" used as a query parameter. -!!! tip - Notice that the query `token` will be handled by a dependency. +/// tip + +Notice that the query `token` will be handled by a dependency. + +/// With that you can connect the WebSocket and then send and receive messages: @@ -185,17 +210,21 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// To try it out: @@ -209,12 +238,15 @@ That will raise the `WebSocketDisconnect` exception, and all the other clients w Client #1596980209979 left the chat ``` -!!! tip - The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. +/// tip + +The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. + +But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. - But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. +If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. - If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. +/// ## More info diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 9a101a8a1..2ad584c95 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -30,12 +30,17 @@ It is used by many companies including Mozilla, Red Hat and Eventbrite. It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**. -!!! note - Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. +/// note +Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. -!!! check "Inspired **FastAPI** to" - Have an automatic API documentation web user interface. +/// + +/// check | "Inspired **FastAPI** to" + +Have an automatic API documentation web user interface. + +/// ### Flask @@ -51,11 +56,13 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -!!! check "Inspired **FastAPI** to" - Be a micro-framework. Making it easy to mix and match the tools and parts needed. +/// check | "Inspired **FastAPI** to" - Have a simple and easy to use routing system. +Be a micro-framework. Making it easy to mix and match the tools and parts needed. +Have a simple and easy to use routing system. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -!!! check "Inspired **FastAPI** to" - * Have a simple and intuitive API. - * Use HTTP method names (operations) directly, in a straightforward and intuitive way. - * Have sensible defaults, but powerful customizations. +/// check | "Inspired **FastAPI** to" + +* Have a simple and intuitive API. +* Use HTTP method names (operations) directly, in a straightforward and intuitive way. +* Have sensible defaults, but powerful customizations. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -!!! check "Inspired **FastAPI** to" - Adopt and use an open standard for API specifications, instead of a custom schema. +/// check | "Inspired **FastAPI** to" + +Adopt and use an open standard for API specifications, instead of a custom schema. - And integrate standards-based user interface tools: +And integrate standards-based user interface tools: - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). +These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). + +/// ### Flask REST frameworks @@ -135,8 +147,11 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow. -!!! check "Inspired **FastAPI** to" - Use code to define "schemas" that provide data types and validation, automatically. +/// check | "Inspired **FastAPI** to" + +Use code to define "schemas" that provide data types and validation, automatically. + +/// ### Webargs @@ -148,11 +163,17 @@ It uses Marshmallow underneath to do the data validation. And it was created by It's a great tool and I have used it a lot too, before having **FastAPI**. -!!! info - Webargs was created by the same Marshmallow developers. +/// info + +Webargs was created by the same Marshmallow developers. + +/// + +/// check | "Inspired **FastAPI** to" -!!! check "Inspired **FastAPI** to" - Have automatic validation of incoming request data. +Have automatic validation of incoming request data. + +/// ### APISpec @@ -172,12 +193,17 @@ But then, we have again the problem of having a micro-syntax, inside of a Python The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete. -!!! info - APISpec was created by the same Marshmallow developers. +/// info + +APISpec was created by the same Marshmallow developers. + +/// +/// check | "Inspired **FastAPI** to" -!!! check "Inspired **FastAPI** to" - Support the open standard for APIs, OpenAPI. +Support the open standard for APIs, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Using it led to the creation of several Flask full-stack generators. These are t And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec was created by the same Marshmallow developers. +/// info + +Flask-apispec was created by the same Marshmallow developers. + +/// -!!! check "Inspired **FastAPI** to" - Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. +/// check | "Inspired **FastAPI** to" + +Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. + +/// ### NestJS (and Angular) @@ -219,24 +251,33 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -!!! check "Inspired **FastAPI** to" - Use Python types to have great editor support. +/// check | "Inspired **FastAPI** to" + +Use Python types to have great editor support. - Have a powerful dependency injection system. Find a way to minimize code repetition. +Have a powerful dependency injection system. Find a way to minimize code repetition. + +/// ### Sanic It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -!!! note "Technical Details" - It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. +/// note | "Technical Details" + +It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. - It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. +It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. -!!! check "Inspired **FastAPI** to" - Find a way to have a crazy performance. +/// - That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). +/// check | "Inspired **FastAPI** to" + +Find a way to have a crazy performance. + +That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). + +/// ### Falcon @@ -246,12 +287,15 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -!!! check "Inspired **FastAPI** to" - Find ways to get great performance. +/// check | "Inspired **FastAPI** to" - Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. +Find ways to get great performance. - Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. +Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. + +Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. + +/// ### Molten @@ -269,10 +313,13 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -!!! check "Inspired **FastAPI** to" - Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. +/// check | "Inspired **FastAPI** to" + +Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. - This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). +This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). + +/// ### Hug @@ -288,15 +335,21 @@ It has an interesting, uncommon feature: using the same framework, it's possible As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too. -!!! info - Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. +/// info + +Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. + +/// -!!! check "Ideas inspiring **FastAPI**" - Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. +/// check | "Ideas inspiring **FastAPI**" - Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. +Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. - Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. +Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. + +Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. + +/// ### APIStar (<= 0.5) @@ -322,23 +375,29 @@ It was no longer an API web framework, as the creator needed to focus on Starlet Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework. -!!! info - APIStar was created by Tom Christie. The same guy that created: +/// info + +APIStar was created by Tom Christie. The same guy that created: - * Django REST Framework - * Starlette (in which **FastAPI** is based) - * Uvicorn (used by Starlette and **FastAPI**) +* Django REST Framework +* Starlette (in which **FastAPI** is based) +* Uvicorn (used by Starlette and **FastAPI**) -!!! check "Inspired **FastAPI** to" - Exist. +/// - The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. +/// check | "Inspired **FastAPI** to" - And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. +Exist. - Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. +The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. - I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. +And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. + +Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. + +I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. + +/// ## Used by **FastAPI** @@ -350,10 +409,13 @@ That makes it extremely intuitive. It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great. -!!! check "**FastAPI** uses it to" - Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). +/// check | "**FastAPI** uses it to" - **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. +Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). + +**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. + +/// ### Starlette @@ -382,17 +444,23 @@ But it doesn't provide automatic data validation, serialization or documentation That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc. -!!! note "Technical Details" - ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. +/// note | "Technical Details" + +ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. - Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. +Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. -!!! check "**FastAPI** uses it to" - Handle all the core web parts. Adding features on top. +/// - The class `FastAPI` itself inherits directly from the class `Starlette`. +/// check | "**FastAPI** uses it to" - So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. +Handle all the core web parts. Adding features on top. + +The class `FastAPI` itself inherits directly from the class `Starlette`. + +So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. + +/// ### Uvicorn @@ -402,12 +470,15 @@ It is not a web framework, but a server. For example, it doesn't provide tools f It is the recommended server for Starlette and **FastAPI**. -!!! check "**FastAPI** recommends it as" - The main web server to run **FastAPI** applications. +/// check | "**FastAPI** recommends it as" + +The main web server to run **FastAPI** applications. + +You can combine it with Gunicorn, to have an asynchronous multi-process server. - You can combine it with Gunicorn, to have an asynchronous multi-process server. +Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. - Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. +/// ## Benchmarks and speed diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 793d691e3..43fd8e70d 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - You can only use `await` inside of functions created with `async def`. +/// note + +You can only use `await` inside of functions created with `async def`. + +/// --- @@ -136,8 +139,11 @@ You and your crush eat the burgers and have a nice time. ✨ -!!! info - Beautiful illustrations by Ketrina Thompson. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ You just eat them, and you are done. ⏹ There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞 -!!! info - Beautiful illustrations by Ketrina Thompson. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -392,12 +401,15 @@ All that is what powers FastAPI (through Starlette) and what makes it have such ## Very Technical Details -!!! warning - You can probably skip this. +/// warning + +You can probably skip this. + +These are very technical details of how **FastAPI** works underneath. - These are very technical details of how **FastAPI** works underneath. +If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. - If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. +/// ### Path operation functions diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index d7ec25dea..e86c34e48 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -24,63 +24,73 @@ That will create a directory `./env/` with the Python binaries, and then you wil Activate the new environment with: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// + +//// tab | Windows Bash - Or if you use Bash for Windows (e.g. Git Bash): +Or if you use Bash for Windows (e.g. Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// To check it worked, use: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` -
+
+ +//// If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip - Every time you install a new package with `pip` under that environment, activate the environment again. +/// tip + +Every time you install a new package with `pip` under that environment, activate the environment again. - This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. +This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. + +/// ### Install requirements using pip @@ -125,10 +138,13 @@ And if you update that local FastAPI source code when you run that Python file a That way, you don't have to "install" your local version to be able to test every change. -!!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. +/// note | "Technical Details" + +This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. +That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + +/// ### Format the code @@ -170,20 +186,23 @@ It will serve the documentation on `http://127.0.0.1:8008`. That way, you can edit the documentation/source files and see the changes live. -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip - Go into the language directory, for the main docs in English it's at `docs/en/`: +Alternatively, you can perform the same steps that scripts does manually. - ```console - $ cd docs/en/ - ``` +Go into the language directory, for the main docs in English it's at `docs/en/`: - Then run `mkdocs` in that directory: +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Then run `mkdocs` in that directory: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer CLI (optional) @@ -210,8 +229,11 @@ The documentation uses add comments with change suggestions to existing pull requests. +/// tip + +You can add comments with change suggestions to existing pull requests. + +Check the docs about adding a pull request review to approve it or request changes. - Check the docs about adding a pull request review to approve it or request changes. +/// * Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. @@ -278,8 +303,11 @@ Let's say you want to translate a page for a language that already has translati In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`. -!!! tip - The main ("official") language is English, located at `docs/en/`. +/// tip + +The main ("official") language is English, located at `docs/en/`. + +/// Now run the live server for the docs in Spanish: @@ -296,20 +324,23 @@ $ python ./scripts/docs.py live es -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip + +Alternatively, you can perform the same steps that scripts does manually. - Go into the language directory, for the Spanish translations it's at `docs/es/`: +Go into the language directory, for the Spanish translations it's at `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +Then run `mkdocs` in that directory: - Then run `mkdocs` in that directory: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// Now you can go to http://127.0.0.1:8008 and see your changes live. @@ -329,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notice that the only change in the path and file name is the language code, from `en` to `es`. +/// tip + +Notice that the only change in the path and file name is the language code, from `en` to `es`. + +/// If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 @@ -365,8 +399,11 @@ That command created a file `docs/ht/mkdocs.yml` with a simple config that inher INHERIT: ../en/mkdocs.yml ``` -!!! tip - You could also simply create that file with those contents manually. +/// tip + +You could also simply create that file with those contents manually. + +/// That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one. diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 9701c67d8..f917d18b3 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -151,10 +151,13 @@ And still, you would probably not want the application to stay dead because ther But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times... -!!! tip - ...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. +/// tip - So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. +...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. + +So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. + +/// You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it. @@ -238,10 +241,13 @@ Here are some possible combinations and strategies: * **Cloud services** that handle this for you * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it. -!!! tip - Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. +/// tip + +Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. + +I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. - I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// ## Previous Steps Before Starting @@ -257,10 +263,13 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. -!!! tip - Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. +/// tip - In that case, you wouldn't have to worry about any of this. 🤷 +Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + +In that case, you wouldn't have to worry about any of this. 🤷 + +/// ### Examples of Previous Steps Strategies @@ -272,8 +281,11 @@ Here are some possible ideas: * A bash script that runs the previous steps and then starts your application * You would still need a way to start/restart *that* bash script, detect errors, etc. -!!! tip - I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// tip + +I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +/// ## Resource Utilization diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 157a3c003..6140b1c42 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -4,8 +4,11 @@ When deploying FastAPI applications a common approach is to build a **Linux cont Using Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others. -!!! tip - In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). +/// tip + +In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). + +///
Dockerfile Preview 👀 @@ -129,8 +132,11 @@ Successfully installed fastapi pydantic -!!! info - There are other formats and tools to define and install package dependencies. +/// info + +There are other formats and tools to define and install package dependencies. + +/// ### Create the **FastAPI** Code @@ -217,8 +223,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`. -!!! tip - Review what each line does by clicking each number bubble in the code. 👆 +/// tip + +Review what each line does by clicking each number bubble in the code. 👆 + +/// You should now have a directory structure like: @@ -288,10 +297,13 @@ $ docker build -t myimage . -!!! tip - Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. +/// tip + +Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. + +In this case, it's the same current directory (`.`). - In this case, it's the same current directory (`.`). +/// ### Start the Docker Container @@ -389,8 +401,11 @@ If we focus just on the **container image** for a FastAPI application (and later It could be another container, for example with Traefik, handling **HTTPS** and **automatic** acquisition of **certificates**. -!!! tip - Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. +/// tip + +Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. + +/// Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container). @@ -418,8 +433,11 @@ When using containers, you would normally have some component **listening on the As this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**. -!!! tip - The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. +/// tip + +The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. + +/// And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app. @@ -498,8 +516,11 @@ If you are using containers (e.g. Docker, Kubernetes), then there are two main a If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers. -!!! info - If you are using Kubernetes, this would probably be an Init Container. +/// info + +If you are using Kubernetes, this would probably be an Init Container. + +/// If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. @@ -515,8 +536,11 @@ This image would be useful mainly in the situations described above in: [Contain * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). +/// warning + +There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). + +/// This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. @@ -524,8 +548,11 @@ It has **sensible defaults**, but you can still change and update all the config It also supports running **previous steps before starting** with a script. -!!! tip - To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. +/// tip + +To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Number of Processes on the Official Docker Image @@ -652,8 +679,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] 11. Use the `fastapi run` command to run your app. -!!! tip - Click the bubble numbers to see what each line does. +/// tip + +Click the bubble numbers to see what each line does. + +/// A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 5cf76c111..46eda791e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -4,8 +4,11 @@ It is easy to assume that HTTPS is something that is just "enabled" or not. But it is way more complex than that. -!!! tip - If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. +/// tip + +If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. + +/// To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. @@ -68,8 +71,11 @@ In the DNS server(s) you would configure a record (an "`A record`") to point **y You would probably do this just once, the first time, when setting everything up. -!!! tip - This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. +/// tip + +This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. + +/// ### DNS @@ -115,8 +121,11 @@ After this, the client and the server have an **encrypted TCP connection**, this And that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection. -!!! tip - Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. +/// tip + +Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. + +/// ### HTTPS Request diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index ad9f62f91..d70c5e48b 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -84,89 +84,106 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca But you can also install an ASGI server manually: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. +* Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
- !!! tip - By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. +/// tip - That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. +By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. - When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. +That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. -=== "Hypercorn" +When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. - * Hypercorn, an ASGI server also compatible with HTTP/2. +/// -
+//// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* Hypercorn, an ASGI server also compatible with HTTP/2. -
+
- ...or any other ASGI server. +```console +$ pip install hypercorn + +---> 100% +``` + +
+ +...or any other ASGI server. + +//// ## Run the Server Program If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +
+ +//// + +//// tab | Hypercorn - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +
-
+```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` -
+
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// note -
+The command `uvicorn main:app` refers to: -!!! note - The command `uvicorn main:app` refers to: +* `main`: the file `main.py` (the Python "module"). +* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. + +It is equivalent to: + +```Python +from main import app +``` - * `main`: the file `main.py` (the Python "module"). - * `app`: the object created inside of `main.py` with the line `app = FastAPI()`. +/// - It is equivalent to: +/// warning - ```Python - from main import app - ``` +Uvicorn and others support a `--reload` option that is useful during development. -!!! warning - Uvicorn and others support a `--reload` option that is useful during development. +The `--reload` option consumes much more resources, is more unstable, etc. - The `--reload` option consumes much more resources, is more unstable, etc. +It helps a lot during **development**, but you **shouldn't** use it in **production**. - It helps a lot during **development**, but you **shouldn't** use it in **production**. +/// ## Hypercorn with Trio diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 5fe2309a9..433371b9d 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ As you saw in the previous chapter about [Deployment Concepts](concepts.md){.int Here I'll show you how to use **Gunicorn** with **Uvicorn worker processes**. -!!! info - If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. +/// info - In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. + +/// ## Gunicorn with Uvicorn Workers diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index 24430b0cf..e387d5712 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -42,8 +42,11 @@ Following the Semantic Versioning conventions, any version below `1.0.0` could p FastAPI also follows the convention that any "PATCH" version change is for bug fixes and non-breaking changes. -!!! tip - The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. +/// tip + +The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. + +/// So, you should be able to pin to a version like: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Breaking changes and new features are added in "MINOR" versions. -!!! tip - The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. +/// tip + +The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. + +/// ## Upgrading the FastAPI versions diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index 1a36390f5..5a3b8ee33 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -6,8 +6,11 @@ There are many posts, articles, tools, and projects, related to **FastAPI**. Here's an incomplete list of some of them. -!!! tip - If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. +/// tip + +If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index 0fc072ed2..e27bebcb4 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -76,5 +76,8 @@ By default, **auto-reload** is disabled. It also listens on the IP address `0.0. In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. -!!! tip - You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. +/// tip + +You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index c9fcc3866..bf7954449 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -64,10 +64,13 @@ These are the users that have been [helping others the most with questions in Gi They have proven to be **FastAPI Experts** by helping many others. ✨ -!!! tip - You could become an official FastAPI Expert too! +/// tip - Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 +You could become an official FastAPI Expert too! + +Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 + +/// You can see the **FastAPI Experts** for: diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index f8954c0fc..1a871a22b 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` means: +/// info - Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` means: + +Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor support diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index ab2dff39b..cd367dd6b 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -170,12 +170,15 @@ And if there's any other style or consistency need, I'll ask directly for that, * Then **comment** saying that you did that, that's how I will know you really checked it. -!!! info - Unfortunately, I can't simply trust PRs that just have several approvals. +/// info - Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 +Unfortunately, I can't simply trust PRs that just have several approvals. - So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 +Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 + +So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 + +/// * If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things. @@ -226,10 +229,13 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 Discord chat server 👥 and hang out with others in the FastAPI community. -!!! tip - For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. +/// tip + +For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Use the chat only for other general conversations. - Use the chat only for other general conversations. +/// ### Don't use the chat for questions diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index 4d53f53a7..a75f8ef58 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -1,14 +1,20 @@ # ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1. -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. + +/// + +/// warning | "Deprecated" + +This tutorial is deprecated and will be removed in a future version. + +/// You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. @@ -22,10 +28,13 @@ In this example, we'll use **SQLite**, because it uses a single file and Python Later, for your production application, you might want to use a database server like **PostgreSQL**. -!!! tip - You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. +/// tip - This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. +You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. + +This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. + +/// ## Import and set up `SQLAlchemy` @@ -37,10 +46,13 @@ Later, for your production application, you might want to use a database server {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! tip - Notice that all this code is pure SQLAlchemy Core. +/// tip + +Notice that all this code is pure SQLAlchemy Core. + +`databases` is not doing anything here yet. - `databases` is not doing anything here yet. +/// ## Import and set up `databases` @@ -52,8 +64,11 @@ Later, for your production application, you might want to use a database server {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! tip - If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. +/// tip + +If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. + +/// ## Create the tables @@ -100,8 +115,11 @@ Create the *path operation function* to read notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. +/// note + +Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. + +/// ### Notice the `response_model=List[Note]` @@ -117,13 +135,19 @@ Create the *path operation function* to create notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info + +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +/// + +/// note - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. -!!! note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. +/// ### About `{**note.dict(), "id": last_record_id}` diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 053e5eacd..0c766d3e4 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -40,12 +40,15 @@ And similarly for ReDoc... {!../../../docs_src/custom_docs_ui/tutorial001.py!} ``` -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +/// tip - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. + +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test it @@ -177,12 +180,15 @@ And similarly for ReDoc... {!../../../docs_src/custom_docs_ui/tutorial002.py!} ``` -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +/// tip + +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. + +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +/// ### Create a *path operation* to test static files diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index 3b9435004..20e1904f1 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ In particular, this may be a good alternative to logic in a middleware. For example, if you want to read or manipulate the request body before it is processed by your application. -!!! danger - This is an "advanced" feature. +/// danger - If you are just starting with **FastAPI** you might want to skip this section. +This is an "advanced" feature. + +If you are just starting with **FastAPI** you might want to skip this section. + +/// ## Use cases @@ -27,8 +30,11 @@ And an `APIRoute` subclass to use that custom request class. ### Create a custom `GzipRequest` class -!!! tip - This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header. @@ -54,16 +60,19 @@ Here we use it to create a `GzipRequest` from the original request. {!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "Technical Details" - A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. +/// note | "Technical Details" - A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. +A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. - The `scope` `dict` and `receive` function are both part of the ASGI specification. +A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. - And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. +The `scope` `dict` and `receive` function are both part of the ASGI specification. - To learn more about the `Request` check Starlette's docs about Requests. +And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. + +To learn more about the `Request` check Starlette's docs about Requests. + +/// The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`. @@ -75,10 +84,13 @@ But because of our changes in `GzipRequest.body`, the request body will be autom ## Accessing the request body in an exception handler -!!! tip - To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). +/// tip + +To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +But this example is still valid and it shows how to interact with the internal components. - But this example is still valid and it shows how to interact with the internal components. +/// We can also use this same approach to access the request body in an exception handler. diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index a18fd737e..9909f778c 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ And that function `get_openapi()` receives as parameters: * `description`: The description of your API, this can include markdown and will be shown in the docs. * `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. -!!! info - The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. +/// info + +The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. + +/// ## Overriding the defaults diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index d5a5826f1..d4b7cfdaa 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -4,12 +4,15 @@ As **FastAPI** is based on the **ASGI** standard, it's very easy to integrate an You can combine normal FastAPI *path operations* with GraphQL on the same application. -!!! tip - **GraphQL** solves some very specific use cases. +/// tip - It has **advantages** and **disadvantages** when compared to common **web APIs**. +**GraphQL** solves some very specific use cases. - Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓 +It has **advantages** and **disadvantages** when compared to common **web APIs**. + +Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓 + +/// ## GraphQL Libraries @@ -46,8 +49,11 @@ Previous versions of Starlette included a `GraphQLApp` class to integrate with < It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to starlette-graphene3, that covers the same use case and has an **almost identical interface**. -!!! tip - If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. +/// tip + +If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. + +/// ## Learn More diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md index ec7fd38f8..730dce5d5 100644 --- a/docs/en/docs/how-to/index.md +++ b/docs/en/docs/how-to/index.md @@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them. -!!! tip +/// tip - If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. +If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. + +/// diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index 18e3f4b7e..a0abfe21d 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -1,14 +1,20 @@ # ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1. +These docs are about to be updated. 🎉 - The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. +The current version assumes Pydantic v1. -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. + +/// + +/// warning | "Deprecated" + +This tutorial is deprecated and will be removed in a future version. + +/// **FastAPI** can also be integrated with any NoSQL. @@ -22,8 +28,11 @@ You can adapt it to any other NoSQL database like: * **ArangoDB** * **ElasticSearch**, etc. -!!! tip - There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase +/// tip + +There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase + +/// ## Import Couchbase components @@ -94,10 +103,13 @@ We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of {!../../../docs_src/nosql_databases/tutorial001.py!} ``` -!!! note - Notice that we have a `hashed_password` and a `type` field that will be stored in the database. +/// note + +Notice that we have a `hashed_password` and a `type` field that will be stored in the database. + +But it is not part of the general `User` model (the one we will return in the *path operation*). - But it is not part of the general `User` model (the one we will return in the *path operation*). +/// ## Get the user diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 10be1071a..0ab5b1337 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,123 @@ Let's see how that works and how to change it if you need to do that. Let's say you have a Pydantic model with default values, like this one: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +```Python hl_lines="7" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - # Code below omitted 👇 - ``` +# Code below omitted 👇 +``` -
- 👀 Full file preview +
+👀 Full file preview - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` -
+
-=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +//// tab | Python 3.9+ - # Code below omitted 👇 - ``` +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} -
- 👀 Full file preview +# Code below omitted 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +
+👀 Full file preview -
+```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +
- ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +//// - # Code below omitted 👇 - ``` +//// tab | Python 3.8+ -
- 👀 Full file preview +```Python hl_lines="9" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +# Code below omitted 👇 +``` -
+
+👀 Full file preview + +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ### Model for Input If you use this model as an input like here: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +# Code below omitted 👇 +``` - # Code below omitted 👇 - ``` +
+👀 Full file preview -
- 👀 Full file preview +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +
-
+//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - # Code below omitted 👇 - ``` +# Code below omitted 👇 +``` -
- 👀 Full file preview +
+👀 Full file preview - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -
+
-=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +//// tab | Python 3.8+ - # Code below omitted 👇 - ``` +```Python hl_lines="16" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} -
- 👀 Full file preview +# Code below omitted 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +
+👀 Full file preview -
+```Python +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ...then the `description` field will **not be required**. Because it has a default value of `None`. @@ -130,23 +142,29 @@ You can confirm that in the docs, the `description` field doesn't have a **red a But if you use the same model as an output, like here: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// ...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. @@ -199,26 +217,35 @@ Probably the main use case for this is if you already have some autogenerated cl In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`. -!!! info - Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 +/// info + +Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +//// ### Same Schema for Input and Output Models in Docs diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md index 7211f7ed3..e411c200c 100644 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -1,28 +1,40 @@ # ~~SQL (Relational) Databases with Peewee~~ (deprecated) -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. +/// warning | "Deprecated" -!!! warning - If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. +This tutorial is deprecated and will be removed in a future version. - Feel free to skip this. +/// - Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. +/// warning -!!! info - These docs assume Pydantic v1. +If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. +Feel free to skip this. - The examples here are no longer tested in CI (as they were before). +Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. + +/// + +/// info + +These docs assume Pydantic v1. + +Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. + +The examples here are no longer tested in CI (as they were before). + +/// If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. -!!! warning "Python 3.7+ required" - You will need Python 3.7 or above to safely use Peewee with FastAPI. +/// warning | "Python 3.7+ required" + +You will need Python 3.7 or above to safely use Peewee with FastAPI. + +/// ## Peewee for async @@ -36,8 +48,11 @@ But if you need to change some of the defaults, support more than one predefined Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. -!!! note "Technical Details" - You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. +/// note | "Technical Details" + +You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. + +/// ## The same app @@ -77,8 +92,11 @@ Let's first check all the normal Peewee code, create a Peewee database: {!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` -!!! tip - Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. +/// tip + +Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. + +/// #### Note @@ -96,9 +114,11 @@ connect_args={"check_same_thread": False} ...it is needed only for `SQLite`. -!!! info "Technical Details" +/// info | "Technical Details" - Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. +Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. + +/// ### Make Peewee async-compatible `PeeweeConnectionState` @@ -106,14 +126,17 @@ The main issue with Peewee and FastAPI is that Peewee relies heavily on { - children.forEach((el, i) => {el.style.display = "none"}); + children.forEach((el, i) => { el.style.display = "none" }); children[index].style.display = "block" index = (index + 1) % children.length } @@ -176,5 +176,6 @@ async function main() { showRandomAnnouncement('announce-left', 5000) showRandomAnnouncement('announce-right', 10000) } - -main() +document$.subscribe(() => { + main() +}) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index efda1a703..2c91cab72 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -2,8 +2,11 @@ These are the tasks that can be performed to manage the FastAPI repository by [team members](./fastapi-people.md#team){.internal-link target=_blank}. -!!! tip - This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉 +/// tip + +This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉 + +/// ...so, you are a [team member of FastAPI](./fastapi-people.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎 @@ -80,8 +83,11 @@ Make sure you use a supported label from the + diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 20ffcdccc..900ede22c 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -12,8 +12,11 @@ This is just a **quick tutorial / refresher** about Python type hints. It covers But even if you never use **FastAPI**, you would benefit from learning a bit about them. -!!! note - If you are a Python expert, and you already know everything about type hints, skip to the next chapter. +/// note + +If you are a Python expert, and you already know everything about type hints, skip to the next chapter. + +/// ## Motivation @@ -170,45 +173,55 @@ If you can use the **latest versions of Python**, use the examples for the lates For example, let's define a variable to be a `list` of `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ - Declare the variable, with the same colon (`:`) syntax. +Declare the variable, with the same colon (`:`) syntax. - As the type, put `list`. +As the type, put `list`. - As the list is a type that contains some internal types, you put them in square brackets: +As the list is a type that contains some internal types, you put them in square brackets: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - From `typing`, import `List` (with a capital `L`): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +From `typing`, import `List` (with a capital `L`): - Declare the variable, with the same colon (`:`) syntax. +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Declare the variable, with the same colon (`:`) syntax. - As the type, put the `List` that you imported from `typing`. +As the type, put the `List` that you imported from `typing`. - As the list is a type that contains some internal types, you put them in square brackets: +As the list is a type that contains some internal types, you put them in square brackets: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! info - Those internal types in the square brackets are called "type parameters". +/// info - In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above). +Those internal types in the square brackets are called "type parameters". + +In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above). + +/// That means: "the variable `items` is a `list`, and each of the items in this list is a `str`". -!!! tip - If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead. +/// tip + +If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead. + +/// By doing that, your editor can provide support even while processing items from the list: @@ -224,17 +237,21 @@ And still, the editor knows it is a `str`, and provides support for that. You would do the same to declare `tuple`s and `set`s: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// This means: @@ -249,17 +266,21 @@ The first type parameter is for the keys of the `dict`. The second type parameter is for the values of the `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// This means: @@ -275,17 +296,21 @@ In Python 3.6 and above (including Python 3.10) you can use the `Union` type fro In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// In both cases this means that `item` could be an `int` or a `str`. @@ -305,23 +330,29 @@ Using `Optional[str]` instead of just `str` will let the editor help you detecti This also means that in Python 3.10, you can use `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "Python 3.8+ alternative" +//// tab | Python 3.8+ alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### Using `Union` or `Optional` @@ -366,47 +397,53 @@ And then you won't have to worry about names like `Optional` and `Union`. 😎 These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example: -=== "Python 3.10+" +//// tab | Python 3.10+ + +You can use the same builtin types as generics (with square brackets and types inside): + +* `list` +* `tuple` +* `set` +* `dict` - You can use the same builtin types as generics (with square brackets and types inside): +And the same as with Python 3.8, from the `typing` module: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (the same as with Python 3.8) +* ...and others. - And the same as with Python 3.8, from the `typing` module: +In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler. - * `Union` - * `Optional` (the same as with Python 3.8) - * ...and others. +//// - In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler. +//// tab | Python 3.9+ -=== "Python 3.9+" +You can use the same builtin types as generics (with square brackets and types inside): - You can use the same builtin types as generics (with square brackets and types inside): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +And the same as with Python 3.8, from the `typing` module: - And the same as with Python 3.8, from the `typing` module: +* `Union` +* `Optional` +* ...and others. - * `Union` - * `Optional` - * ...and others. +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...and others. +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...and others. + +//// ### Classes as types @@ -446,55 +483,71 @@ And you get all the editor support with that resulting object. An example from the official Pydantic docs: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// tab | Python 3.8+ -!!! info - To learn more about Pydantic, check its docs. +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +To learn more about Pydantic, check its docs. + +/// **FastAPI** is all based on Pydantic. You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. +/// tip + +Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. + +/// ## Type Hints with Metadata Annotations Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +In versions below Python 3.9, you import `Annotated` from `typing_extensions`. - In versions below Python 3.9, you import `Annotated` from `typing_extensions`. +It will already be installed with **FastAPI**. - It will already be installed with **FastAPI**. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`. @@ -506,10 +559,13 @@ For now, you just need to know that `Annotated` exists, and that it's standard P Later you will see how **powerful** it can be. -!!! tip - The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨ +/// tip - And also that your code will be very compatible with many other Python tools and libraries. 🚀 +The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨ + +And also that your code will be very compatible with many other Python tools and libraries. 🚀 + +/// ## Type hints in **FastAPI** @@ -533,5 +589,8 @@ This might all sound abstract. Don't worry. You'll see all this in action in the The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you. -!!! info - If you already went through all the tutorial and came back to see more about types, a good resource is the "cheat sheet" from `mypy`. +/// info + +If you already went through all the tutorial and came back to see more about types, a good resource is the "cheat sheet" from `mypy`. + +/// diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md index 0326f3fc7..f1de21642 100644 --- a/docs/en/docs/reference/request.md +++ b/docs/en/docs/reference/request.md @@ -8,7 +8,10 @@ You can import it directly from `fastapi`: from fastapi import Request ``` -!!! tip - When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. +/// tip + +When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. + +/// ::: fastapi.Request diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md index d21e81a07..4b7244e08 100644 --- a/docs/en/docs/reference/websockets.md +++ b/docs/en/docs/reference/websockets.md @@ -8,8 +8,11 @@ It is provided directly by Starlette, but you can import it from `fastapi`: from fastapi import WebSocket ``` -!!! tip - When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. +/// tip + +When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`. + +/// ::: fastapi.WebSocket options: diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index bcfadc8b8..5370b9ba8 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ Using `BackgroundTasks` also works with the dependency injection system, you can **FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// In this example, the messages will be written to the `log.txt` file *after* the response is sent. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index eccdd8aeb..97f6b205b 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ If you are building an application or a web API, it's rarely the case that you c **FastAPI** provides a convenience tool to structure your application while keeping all the flexibility. -!!! info - If you come from Flask, this would be the equivalent of Flask's Blueprints. +/// info + +If you come from Flask, this would be the equivalent of Flask's Blueprints. + +/// ## An example file structure @@ -26,16 +29,19 @@ Let's say you have a file structure like this: │   └── admin.py ``` -!!! tip - There are several `__init__.py` files: one in each directory or subdirectory. +/// tip + +There are several `__init__.py` files: one in each directory or subdirectory. - This is what allows importing code from one file into another. +This is what allows importing code from one file into another. - For example, in `app/main.py` you could have a line like: +For example, in `app/main.py` you could have a line like: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`. * It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`. @@ -99,8 +105,11 @@ All the same options are supported. All the same `parameters`, `responses`, `dependencies`, `tags`, etc. -!!! tip - In this example, the variable is called `router`, but you can name it however you want. +/// tip + +In this example, the variable is called `router`, but you can name it however you want. + +/// We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`. @@ -112,31 +121,43 @@ So we put them in their own `dependencies` module (`app/dependencies.py`). We will now use a simple dependency to read a custom `X-Token` header: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` - ```Python hl_lines="3 6-8" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 5-7" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} - ``` +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 4-6" title="app/dependencies.py" - {!> ../../../docs_src/bigger_applications/app/dependencies.py!} - ``` +/// tip -!!! tip - We are using an invented header to simplify this example. +Prefer to use the `Annotated` version if possible. - But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}. +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip + +We are using an invented header to simplify this example. + +But in real cases you will get better results using the integrated [Security utilities](security/index.md){.internal-link target=_blank}. + +/// ## Another module with `APIRouter` @@ -180,8 +201,11 @@ We can also add a list of `tags` and extra `responses` that will be applied to a And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them. -!!! tip - Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*. +/// tip + +Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*. + +/// The end result is that the item paths are now: @@ -198,11 +222,17 @@ The end result is that the item paths are now: * The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies. * You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them. +/// tip + +Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them. + +/// + +/// check -!!! check - The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication. +The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication. + +/// ### Import the dependencies @@ -218,8 +248,11 @@ So we use a relative import with `..` for the dependencies: #### How relative imports work -!!! tip - If you know perfectly how imports work, continue to the next section below. +/// tip + +If you know perfectly how imports work, continue to the next section below. + +/// A single dot `.`, like in: @@ -286,10 +319,13 @@ But we can still add _more_ `tags` that will be applied to a specific *path oper {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - This last path operation will have the combination of tags: `["items", "custom"]`. +/// tip - And it will also have both responses in the documentation, one for `404` and one for `403`. +This last path operation will have the combination of tags: `["items", "custom"]`. + +And it will also have both responses in the documentation, one for `404` and one for `403`. + +/// ## The main `FastAPI` @@ -345,20 +381,23 @@ We could also import them like: from app.routers import items, users ``` -!!! info - The first version is a "relative import": +/// info - ```Python - from .routers import items, users - ``` +The first version is a "relative import": - The second version is an "absolute import": +```Python +from .routers import items, users +``` + +The second version is an "absolute import": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +To learn more about Python Packages and Modules, read the official Python documentation about Modules. - To learn more about Python Packages and Modules, read the official Python documentation about Modules. +/// ### Avoid name collisions @@ -389,26 +428,35 @@ Now, let's include the `router`s from the submodules `users` and `items`: {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` contains the `APIRouter` inside of the file `app/routers/users.py`. +/// info + +`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`. - And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`. +And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`. + +/// With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application. It will include all the routes from that router as part of it. -!!! note "Technical Details" - It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`. +/// note | "Technical Details" + +It will actually internally create a *path operation* for each *path operation* that was declared in the `APIRouter`. + +So, behind the scenes, it will actually work as if everything was the same single app. - So, behind the scenes, it will actually work as if everything was the same single app. +/// -!!! check - You don't have to worry about performance when including routers. +/// check - This will take microseconds and will only happen at startup. +You don't have to worry about performance when including routers. - So it won't affect performance. ⚡ +This will take microseconds and will only happen at startup. + +So it won't affect performance. ⚡ + +/// ### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies` @@ -455,16 +503,19 @@ Here we do it... just to show that we can 🤷: and it will work correctly, together with all the other *path operations* added with `app.include_router()`. -!!! info "Very Technical Details" - **Note**: this is a very technical detail that you probably can **just skip**. +/// info | "Very Technical Details" + +**Note**: this is a very technical detail that you probably can **just skip**. + +--- - --- +The `APIRouter`s are not "mounted", they are not isolated from the rest of the application. - The `APIRouter`s are not "mounted", they are not isolated from the rest of the application. +This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces. - This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces. +As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly. - As we cannot just isolate them and "mount" them independently of the rest, the *path operations* are "cloned" (re-created), not included directly. +/// ## Check the automatic API docs diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 55e67fdd6..466df29f1 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ The same way you can declare additional validation and metadata in *path operati First, you have to import it: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc). +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning + +Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc). + +/// ## Declare model attributes You can then use `Field` with model attributes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc. -!!! note "Technical Details" - Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class. +/// note | "Technical Details" - And Pydantic's `Field` returns an instance of `FieldInfo` as well. +Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class. - `Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class. +And Pydantic's `Field` returns an instance of `FieldInfo` as well. - Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes. +`Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class. -!!! tip - Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`. +Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes. + +/// + +/// tip + +Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`. + +/// ## Add extra information @@ -105,9 +146,12 @@ You can declare extra information in `Field`, `Query`, `Body`, etc. And it will You will learn more about adding extra information later in the docs, when learning to declare examples. -!!! warning - Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application. - As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema. +/// warning + +Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application. +As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema. + +/// ## Recap diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 689db7ece..3adfcd4d1 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara And you can also declare body parameters as optional, by setting the default to `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip -!!! note - Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note + +Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. + +/// ## Multiple body parameters @@ -62,17 +81,21 @@ In the previous example, the *path operations* would expect a JSON body with the But you can also declare multiple body parameters, e.g. `item` and `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models). @@ -93,9 +116,11 @@ So, it will then use the parameter names as keys (field names) in the body, and } ``` -!!! note - Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. +/// note + +Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. +/// **FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`. @@ -111,41 +136,57 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume But you can instruct **FastAPI** to treat it as another body key using `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +/// + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +//// In this case, **FastAPI** will expect a body like: @@ -185,44 +226,63 @@ q: str | None = None For example: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later. -!!! info - `Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later. +/// ## Embed a single body parameter @@ -238,41 +298,57 @@ item: Item = Body(embed=True) as in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// In this case **FastAPI** will expect a body like: diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 4c199f028..f823a9033 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply You can define an attribute to be a subtype. For example, a Python `list`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// This will make `tags` be a list, although it doesn't declare the type of the elements of the list. @@ -61,23 +65,29 @@ Use that same standard syntax for model attributes with internal types. So, in our example, we can make `tags` be specifically a "list of strings": -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set types @@ -87,23 +97,29 @@ And Python has a special data type for sets of unique items, the `set`. Then we can declare `tags` as a set of strings: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// With this, even if you receive a request with duplicate data, it will be converted to a set of unique items. @@ -125,45 +141,57 @@ All that, arbitrarily nested. For example, we can define an `Image` model: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Use the submodel as a type And then we can use it as the type of an attribute: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// This would mean that **FastAPI** would expect a body similar to: @@ -196,23 +224,29 @@ To see all the options you have, checkout the docs for ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such. @@ -220,23 +254,29 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op You can also use Pydantic models as subtypes of `list`, `set`, etc.: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// This will expect (convert, validate, document, etc.) a JSON body like: @@ -264,33 +304,45 @@ This will expect (convert, validate, document, etc.) a JSON body like: } ``` -!!! info - Notice how the `images` key now has a list of image objects. +/// info + +Notice how the `images` key now has a list of image objects. + +/// ## Deeply nested models You can define arbitrarily deeply nested models: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s -!!! info - Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s +/// ## Bodies of pure lists @@ -308,17 +360,21 @@ images: list[Image] as in: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Editor support everywhere @@ -348,26 +404,33 @@ That's what we are going to see here. In this case, you would accept any `dict` as long as it has `int` keys with `float` values: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Keep in mind that JSON only supports `str` as keys. -!!! tip - Keep in mind that JSON only supports `str` as keys. +But Pydantic has automatic data conversion. - But Pydantic has automatic data conversion. +This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them. - This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them. +And the `dict` you receive as `weights` will actually have `int` keys and `float` values. - And the `dict` you receive as `weights` will actually have `int` keys and `float` values. +/// ## Recap diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3ba2632d8..261f44d33 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ To update an item you can use the ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// `PUT` is used to receive data that should replace the existing data. @@ -48,14 +54,17 @@ You can also use the ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Using Pydantic's `update` parameter Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update. -!!! info - In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. +/// info + +In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. - The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. +The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. + +/// Like `stored_item_model.model_copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Partial updates recap @@ -134,32 +161,44 @@ In summary, to apply partial updates you would: * Save the data to your DB. * Return the updated model. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +You can actually use this same technique with an HTTP `PUT` operation. -=== "Python 3.8+" +But the example here uses `PATCH` because it was created for these use cases. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip - You can actually use this same technique with an HTTP `PUT` operation. +/// note - But the example here uses `PATCH` because it was created for these use cases. +Notice that the input model is still validated. -!!! note - Notice that the input model is still validated. +So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`). - So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`). +To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}. - To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index f9af42938..f3a8685c6 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -8,28 +8,35 @@ Your API almost always has to send a **response** body. But clients don't necess To declare a **request** body, you use Pydantic models with all their power and benefits. -!!! info - To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. +/// info - Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases. +To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`. - As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it. +Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases. + +As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it. + +/// ## Import Pydantic's `BaseModel` First, you need to import `BaseModel` from `pydantic`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## Create your data model @@ -37,17 +44,21 @@ Then you declare your data model as a class that inherits from `BaseModel`. Use standard Python types for all the attributes: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional. @@ -75,17 +86,21 @@ For example, this model above declares a JSON "`object`" (or Python `dict`) like To add it to your *path operation*, declare it the same way you declared path and query parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ...and declare its type as the model you created, `Item`. @@ -134,32 +149,39 @@ But you would get the same editor support with -!!! tip - If you use PyCharm as your editor, you can use the Pydantic PyCharm Plugin. +/// tip + +If you use PyCharm as your editor, you can use the Pydantic PyCharm Plugin. - It improves editor support for Pydantic models, with: +It improves editor support for Pydantic models, with: - * auto-completion - * type checks - * refactoring - * searching - * inspections +* auto-completion +* type checks +* refactoring +* searching +* inspections + +/// ## Use the model Inside of the function, you can access all the attributes of the model object directly: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## Request body + path parameters @@ -167,17 +189,21 @@ You can declare path parameters and request body at the same time. **FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## Request body + path + query parameters @@ -185,17 +211,21 @@ You can also declare **body**, **path** and **query** parameters, all at the sam **FastAPI** will recognize each of them and take the data from the correct place. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// The function parameters will be recognized as follows: @@ -203,10 +233,13 @@ The function parameters will be recognized as follows: * If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter. * If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**. -!!! note - FastAPI will know that the value of `q` is not required because of the default value `= None`. +/// note + +FastAPI will know that the value of `q` is not required because of the default value `= None`. + +The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. - The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. +/// ## Without Pydantic diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 3436a7df3..6196b34d0 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ You can define Cookie parameters the same way you define `Query` and `Path` para First import `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Declare `Cookie` parameters @@ -48,49 +64,71 @@ Then declare the cookie parameters using the same structure as with `Path` and ` The first value is the default value, you can pass all the extra validation or annotation parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Technical Details" -=== "Python 3.8+ non-Annotated" +`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class. - !!! tip - Prefer to use the `Annotated` version if possible. +But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Technical Details" - `Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class. +/// info - But remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes. +To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters. -!!! info - To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters. +/// ## Recap diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 33b11983b..665249ffa 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Any request with an `Origin` header. In this case the middleware will pass the r For more info about CORS, check the Mozilla CORS documentation. -!!! note "Technical Details" - You could also use `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Technical Details" - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +You could also use `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index 3deba54d5..c520a631d 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ So, the line: will not be executed. -!!! info - For more information, check the official Python docs. +/// info + +For more information, check the official Python docs. + +/// ## Run your code with your debugger diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index 4b958a665..a392672bb 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the In the previous example, we were returning a `dict` from our dependency ("dependable"): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// But then we get a `dict` in the parameter `commons` of the *path operation function*. @@ -103,117 +119,165 @@ That also applies to callables with no parameters at all. The same as it would b Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Pay attention to the `__init__` method used to create the instance of the class: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...it has the same parameters as our previous `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Those parameters are what **FastAPI** will use to "solve" the dependency. @@ -229,41 +293,57 @@ In both cases the data will be converted, validated, documented on the OpenAPI s Now you can declare your dependency using this class. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function. @@ -271,20 +351,27 @@ Now you can declare your dependency using this class. Notice how we write `CommonQueryParams` twice in the above code: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// The last `CommonQueryParams`, in: @@ -300,77 +387,107 @@ From it is that FastAPI will extract the declared parameters and that is what Fa In this case, the first `CommonQueryParams`, in: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that). You could actually write just: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python - commons = Depends(CommonQueryParams) - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ...as in: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc: @@ -380,20 +497,27 @@ But declaring the type is encouraged as that way your editor will know what will But you see that we are having some code repetition here, writing `CommonQueryParams` twice: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// **FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself. @@ -401,81 +525,114 @@ For those specific cases, you can do the following: Instead of writing: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...you write: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.8 non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8 non-Annotated - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`. The same example would then look like: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ...and **FastAPI** will know what to do. -!!! tip - If that seems more confusing than helpful, disregard it, you don't *need* it. +/// tip + +If that seems more confusing than helpful, disregard it, you don't *need* it. + +It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition. - It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition. +/// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 082417f11..7c3ac7922 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ The *path operation decorator* receives an optional argument `dependencies`. It should be a `list` of `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. -!!! tip - Some editors check for unused function parameters, and show them as errors. +/// tip + +Some editors check for unused function parameters, and show them as errors. - Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors. +Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors. - It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary. +It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary. -!!! info - In this example we use invented custom headers `X-Key` and `X-Token`. +/// - But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}. +/// info + +In this example we use invented custom headers `X-Key` and `X-Token`. + +But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}. + +/// ## Dependencies errors and return values @@ -57,51 +72,69 @@ You can use the same dependency *functions* you use normally. They can declare request requirements (like headers) or other sub-dependencies: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8 non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Raise exceptions These dependencies can `raise` exceptions, the same as normal dependencies: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 non-Annotated - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip -=== "Python 3.8 non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Return values @@ -109,26 +142,35 @@ And they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependencies for a group of *path operations* diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index ad5aed932..279fc4d1e 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI supports dependencies that do some Context Managers. +/// note | "Technical Details" + +This works thanks to Python's Context Managers. - **FastAPI** uses them internally to achieve this. +**FastAPI** uses them internally to achieve this. + +/// ## Dependencies with `yield` and `HTTPException` @@ -133,32 +163,43 @@ You saw that you can use dependencies with `yield` and have `try` blocks that ca The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`. -!!! tip +/// tip + +This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. - This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. +But it's there for you if you need it. 🤓 - But it's there for you if you need it. 🤓 +/// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18-22 31" +{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` - ```Python hl_lines="18-22 31" - {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17-21 30" +{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17-21 30" - {!> ../../../docs_src/dependencies/tutorial008b_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="16-20 29" - {!> ../../../docs_src/dependencies/tutorial008b.py!} - ``` +/// + +```Python hl_lines="16-20 29" +{!> ../../../docs_src/dependencies/tutorial008b.py!} +``` + +//// An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -166,26 +207,35 @@ An alternative you could use to catch exceptions (and possibly also raise anothe If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +``` + +//// - ```Python hl_lines="15-16" - {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="14-15" +{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="14-15" - {!> ../../../docs_src/dependencies/tutorial008c_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="13-14" - {!> ../../../docs_src/dependencies/tutorial008c.py!} - ``` +/// + +```Python hl_lines="13-14" +{!> ../../../docs_src/dependencies/tutorial008c.py!} +``` + +//// In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 @@ -195,27 +245,35 @@ If you catch an exception in a dependency with `yield`, unless you are raising a You can re-raise the same exception using `raise`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial008d_an.py!} - ``` +//// +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial008d.py!} - ``` +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial008d.py!} +``` + +//// Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 @@ -258,22 +316,31 @@ participant tasks as Background tasks end ``` -!!! info - Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*. +/// info + +Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*. + +After one of those responses is sent, no other response can be sent. + +/// + +/// tip - After one of those responses is sent, no other response can be sent. +This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -!!! tip - This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. - If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled. +/// ## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks -!!! warning - You most probably don't need these technical details, you can skip this section and continue below. +/// warning - These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. +You most probably don't need these technical details, you can skip this section and continue below. + +These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. + +/// ### Dependencies with `yield` and `except`, Technical Details @@ -289,11 +356,13 @@ This was designed this way mainly to allow using the same objects "yielded" by d Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. -!!! tip +/// tip - Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). +Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). - So, this way you will probably have cleaner code. +So, this way you will probably have cleaner code. + +/// If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. @@ -321,10 +390,13 @@ When you create a dependency with `yield`, **FastAPI** will internally create a ### Using context managers in dependencies with `yield` -!!! warning - This is, more or less, an "advanced" idea. +/// warning + +This is, more or less, an "advanced" idea. - If you are just starting with **FastAPI** you might want to skip it for now. +If you are just starting with **FastAPI** you might want to skip it for now. + +/// In Python, you can create Context Managers by creating a class with two methods: `__enter__()` and `__exit__()`. @@ -335,16 +407,19 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - Another way to create a context manager is with: +/// tip + +Another way to create a context manager is with: + +* `@contextlib.contextmanager` or +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` or - * `@contextlib.asynccontextmanager` +using them to decorate a function with a single `yield`. - using them to decorate a function with a single `yield`. +That's what **FastAPI** uses internally for dependencies with `yield`. - That's what **FastAPI** uses internally for dependencies with `yield`. +But you don't have to use the decorators for FastAPI dependencies (and you shouldn't). - But you don't have to use the decorators for FastAPI dependencies (and you shouldn't). +FastAPI will do it for you internally. - FastAPI will do it for you internally. +/// diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 0dcf73176..03a9a42f0 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ Similar to the way you can [add `dependencies` to the *path operation decorators In that case, they will be applied to all the *path operations* in the application: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app. diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index e05d40685..a608222f2 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ Let's first focus on the dependency. It is just a function that can take all the same parameters that a *path operation function* can take: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// That's it. @@ -85,90 +101,125 @@ In this case, this dependency expects: And then it just returns a `dict` containing those values. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +/// info + +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. - If you have an older version, you would get errors when trying to use `Annotated`. +If you have an older version, you would get errors when trying to use `Annotated`. - Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. + +/// ### Import `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Declare the dependency, in the "dependant" The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently. @@ -180,8 +231,11 @@ You **don't call it** directly (don't add the parenthesis at the end), you just And that function takes parameters in the same way that *path operation functions* do. -!!! tip - You'll see what other "things", apart from functions, can be used as dependencies in the next chapter. +/// tip + +You'll see what other "things", apart from functions, can be used as dependencies in the next chapter. + +/// Whenever a new request arrives, **FastAPI** will take care of: @@ -202,10 +256,13 @@ common_parameters --> read_users This way you write shared code once and **FastAPI** takes care of calling it for your *path operations*. -!!! check - Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar. +/// check + +Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar. + +You just pass it to `Depends` and **FastAPI** knows how to do the rest. - You just pass it to `Depends` and **FastAPI** knows how to do the rest. +/// ## Share `Annotated` dependencies @@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)] But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip -!!! tip - This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**. +This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**. - But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎 +But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎 + +/// The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`. @@ -256,8 +322,11 @@ And you can declare dependencies with `async def` inside of normal `def` *path o It doesn't matter. **FastAPI** will know what to do. -!!! note - If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs. +/// note + +If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry){.internal-link target=_blank} section about `async` and `await` in the docs. + +/// ## Integrated with OpenAPI diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index e5def9b7d..85b252e13 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ They can be as **deep** as you need them to be. You could create a first dependency ("dependable") like: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.10 non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// It declares an optional query parameter `q` as a `str`, and then it just returns it. @@ -54,41 +70,57 @@ This is quite simple (not very useful), but will help us focus on how the sub-de Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Let's focus on the parameters declared: @@ -101,46 +133,65 @@ Let's focus on the parameters declared: Then we can use the dependency with: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8 non-Annotated" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info -!!! info - Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`. +Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`. - But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it. +But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ And it will save the returned value in a ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`. @@ -38,5 +42,8 @@ The result of calling it is something that can be encoded with the Python standa It doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON. -!!! note - `jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios. +/// note + +`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios. + +/// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index e705a18e4..aed9f7880 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ Here are some of the additional data types you can use: Here's an example *path operation* with parameters using some of the above types. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index cc0680cfd..982f59782 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -8,31 +8,41 @@ This is especially the case for user models, because: * The **output model** should not have a password. * The **database model** would probably need to have a hashed password. -!!! danger - Never store user's plaintext passwords. Always store a "secure hash" that you can then verify. +/// danger - If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Never store user's plaintext passwords. Always store a "secure hash" that you can then verify. + +If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Multiple models Here's a general idea of how the models could look like with their password fields and the places where they are used: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +/// ### About `**user_in.dict()` @@ -144,8 +154,11 @@ UserInDB( ) ``` -!!! warning - The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. +/// warning + +The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. + +/// ## Reduce duplication @@ -163,17 +176,21 @@ All the data conversion, validation, documentation, etc. will still work as norm That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` or `anyOf` @@ -183,20 +200,27 @@ It will be defined in OpenAPI with `anyOf`. To do that, use the standard Python type hint `typing.Union`: -!!! note - When defining a `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. +/// note -=== "Python 3.10+" +When defining a `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`. - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` in Python 3.10 @@ -218,17 +242,21 @@ The same way, you can declare responses of lists of objects. For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// ## Response with arbitrary `dict` @@ -238,17 +266,21 @@ This is useful if you don't know the valid field/attribute names (that would be In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index d18b25d97..b48a0ee38 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -163,10 +163,13 @@ You could also use it to generate code automatically, for clients that communica `FastAPI` is a Python class that provides all the functionality for your API. -!!! note "Technical Details" - `FastAPI` is a class that inherits directly from `Starlette`. +/// note | "Technical Details" - You can use all the Starlette functionality with `FastAPI` too. +`FastAPI` is a class that inherits directly from `Starlette`. + +You can use all the Starlette functionality with `FastAPI` too. + +/// ### Step 2: create a `FastAPI` "instance" @@ -196,8 +199,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - A "path" is also commonly called an "endpoint" or a "route". +/// info + +A "path" is also commonly called an "endpoint" or a "route". + +/// While building an API, the "path" is the main way to separate "concerns" and "resources". @@ -247,16 +253,19 @@ The `@app.get("/")` tells **FastAPI** that the function right below is in charge * the path `/` * using a get operation -!!! info "`@decorator` Info" - That `@something` syntax in Python is called a "decorator". +/// info | "`@decorator` Info" + +That `@something` syntax in Python is called a "decorator". - You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from). +You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from). - A "decorator" takes the function below and does something with it. +A "decorator" takes the function below and does something with it. - In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`. +In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`. - It is the "**path operation decorator**". +It is the "**path operation decorator**". + +/// You can also use the other operations: @@ -271,14 +280,17 @@ And the more exotic ones: * `@app.patch()` * `@app.trace()` -!!! tip - You are free to use each operation (HTTP method) as you wish. +/// tip + +You are free to use each operation (HTTP method) as you wish. + +**FastAPI** doesn't enforce any specific meaning. - **FastAPI** doesn't enforce any specific meaning. +The information here is presented as a guideline, not a requirement. - The information here is presented as a guideline, not a requirement. +For example, when using GraphQL you normally perform all the actions using only `POST` operations. - For example, when using GraphQL you normally perform all the actions using only `POST` operations. +/// ### Step 4: define the **path operation function** @@ -306,8 +318,11 @@ You could also define it as a normal function instead of `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Step 5: return the content diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 6133898e4..ca3cff661 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_ } ``` -!!! tip - When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. +/// tip - You could pass a `dict`, a `list`, etc. +When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. - They are handled automatically by **FastAPI** and converted to JSON. +You could pass a `dict`, a `list`, etc. + +They are handled automatically by **FastAPI** and converted to JSON. + +/// ## Add custom headers @@ -106,10 +109,13 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Technical Details" - You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. +/// note | "Technical Details" + +You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. +/// ## Override the default exception handlers @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` vs `ValidationError` -!!! warning - These are technical details that you might skip if it's not important for you now. +/// warning + +These are technical details that you might skip if it's not important for you now. + +/// `RequestValidationError` is a sub-class of Pydantic's `ValidationError`. @@ -183,10 +192,13 @@ For example, you could want to return a plain text response instead of JSON for {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.responses import PlainTextResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import PlainTextResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ### Use the `RequestValidationError` body diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index bbba90998..cc5975b85 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co First import `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// ## Declare `Header` parameters @@ -48,49 +64,71 @@ Then declare the header parameters using the same structure as with `Path`, `Que The first value is the default value, you can pass all the extra validation or annotation parameters: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! note "Technical Details" - `Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. +/// - But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes. +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info - To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters. +//// + +/// note | "Technical Details" + +`Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. + +But remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes. + +/// + +/// info + +To declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters. + +/// ## Automatic conversion @@ -108,44 +146,63 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! warning - Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// warning + +Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. + +/// ## Duplicate headers @@ -157,50 +214,71 @@ You will receive all the values from the duplicate header as a Python `list`. For example, to declare a header of `X-Token` that can appear more than once, you can write: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.9+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// If you communicate with that *path operation* sending two HTTP headers like: diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index f22dc01dd..5f8c51c4c 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -83,10 +83,13 @@ $ pip install "fastapi[standard]" -!!! note - When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. +/// note - If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. +When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. + +If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. + +/// ## Advanced User Guide diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index 4dce9af13..c62509b8b 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -22,8 +22,11 @@ You can set them as follows: {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip - You can write Markdown in the `description` field and it will be rendered in the output. +/// tip + +You can write Markdown in the `description` field and it will be rendered in the output. + +/// With this configuration, the automatic API docs would look like: @@ -65,8 +68,11 @@ Create metadata for your tags and pass it to the `openapi_tags` parameter: Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). -!!! tip - You don't have to add metadata for all the tags that you use. +/// tip + +You don't have to add metadata for all the tags that you use. + +/// ### Use your tags @@ -76,8 +82,11 @@ Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assig {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info - Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}. +/// info + +Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// ### Check the docs diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 492a1b065..f0b3faf3b 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ A "middleware" is a function that works with every **request** before it is proc * It can do something to that **response** or run any needed code. * Then it returns the **response**. -!!! note "Technical Details" - If you have dependencies with `yield`, the exit code will run *after* the middleware. +/// note | "Technical Details" - If there were any background tasks (documented later), they will run *after* all the middleware. +If you have dependencies with `yield`, the exit code will run *after* the middleware. + +If there were any background tasks (documented later), they will run *after* all the middleware. + +/// ## Create a middleware @@ -32,15 +35,21 @@ The middleware function receives: {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - Keep in mind that custom proprietary headers can be added using the 'X-' prefix. +/// tip + +Keep in mind that custom proprietary headers can be added using the 'X-' prefix. + +But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. + +/// + +/// note | "Technical Details" - But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. +You could also use `from starlette.requests import Request`. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +**FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette. +/// ### Before and after the `response` diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index babf85acb..a1a4953a6 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ There are several parameters that you can pass to your *path operation decorator* to configure it. -!!! warning - Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*. +/// warning + +Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*. + +/// ## Response Status Code @@ -13,52 +16,67 @@ You can pass directly the `int` code, like `404`. But if you don't remember what each number code is for, you can use the shortcut constants in `status`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// That status code will be used in the response and will be added to the OpenAPI schema. -!!! note "Technical Details" - You could also use `from starlette import status`. +/// note | "Technical Details" + +You could also use `from starlette import status`. + +**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. +/// ## Tags You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// They will be added to the OpenAPI schema and used by the automatic documentation interfaces: @@ -80,23 +98,29 @@ In these cases, it could make sense to store the tags in an `Enum`. You can add a `summary` and `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Description from docstring @@ -104,23 +128,29 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// It will be used in the interactive docs: @@ -130,31 +160,43 @@ It will be used in the interactive docs: You can specify the response description with the parameter `response_description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check -!!! info - Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general. +OpenAPI specifies that each *path operation* requires a response description. -!!! check - OpenAPI specifies that each *path operation* requires a response description. +So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response". - So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response". +/// diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index ca86ad226..bd835d0d4 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ In the same way that you can declare more validations and metadata for query par First, import `Path` from `fastapi`, and import `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +If you have an older version, you would get errors when trying to use `Annotated`. - If you have an older version, you would get errors when trying to use `Annotated`. +Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. - Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +/// ## Declare metadata @@ -55,49 +74,71 @@ You can declare all the same parameters as for `Query`. For example, to declare a `title` metadata value for the path parameter `item_id` you can type: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. -!!! note - A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. + +/// ## Order the parameters as you need -!!! tip - This is probably not as important or necessary if you use `Annotated`. +/// tip + +This is probably not as important or necessary if you use `Annotated`. + +/// Let's say that you want to declare the query parameter `q` as a required `str`. @@ -113,33 +154,45 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names, So, you can declare your function as: -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Order the parameters as you need, tricks -!!! tip - This is probably not as important or necessary if you use `Annotated`. +/// tip + +This is probably not as important or necessary if you use `Annotated`. + +/// Here's a **small trick** that can be handy, but you won't need it often. @@ -164,17 +217,21 @@ Python won't do anything with that `*`, but it will know that all the following Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Number validations: greater than or equal @@ -182,26 +239,35 @@ With `Query` and `Path` (and others you'll see later) you can declare number con Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Number validations: greater than and less than or equal @@ -210,26 +276,35 @@ The same applies for: * `gt`: `g`reater `t`han * `le`: `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Number validations: floats, greater than and less than @@ -241,26 +316,35 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not. And the same for lt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Recap @@ -273,18 +357,24 @@ And you can also declare numeric validations: * `lt`: `l`ess `t`han * `le`: `l`ess than or `e`qual -!!! info - `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class. +/// info + +`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class. + +All of them share the same parameters for additional validation and metadata you have seen. + +/// + +/// note | "Technical Details" - All of them share the same parameters for additional validation and metadata you have seen. +When you import `Query`, `Path` and others from `fastapi`, they are actually functions. -!!! note "Technical Details" - When you import `Query`, `Path` and others from `fastapi`, they are actually functions. +That when called, return instances of classes of the same name. - That when called, return instances of classes of the same name. +So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`. - So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`. +These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types. - These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types. +That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors. - That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors. +/// diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index 6246d6680..a87a29e08 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ You can declare the type of a path parameter in the function, using standard Pyt In this case, `item_id` is declared to be an `int`. -!!! check - This will give you editor support inside of your function, with error checks, completion, etc. +/// check + +This will give you editor support inside of your function, with error checks, completion, etc. + +/// ## Data conversion @@ -35,10 +38,13 @@ If you run this example and open your browser at "parsing". - So, with that type declaration, **FastAPI** gives you automatic request "parsing". +/// ## Data validation @@ -65,12 +71,15 @@ because the path parameter `item_id` had a value of `"foo"`, which is not an `in The same error would appear if you provided a `float` instead of an `int`, as in: http://127.0.0.1:8000/items/4.2 -!!! check - So, with the same Python type declaration, **FastAPI** gives you data validation. +/// check - Notice that the error also clearly states exactly the point where the validation didn't pass. +So, with the same Python type declaration, **FastAPI** gives you data validation. - This is incredibly helpful while developing and debugging code that interacts with your API. +Notice that the error also clearly states exactly the point where the validation didn't pass. + +This is incredibly helpful while developing and debugging code that interacts with your API. + +/// ## Documentation @@ -78,10 +87,13 @@ And when you open your browser at -!!! check - Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI). +/// check + +Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI). + +Notice that the path parameter is declared to be an integer. - Notice that the path parameter is declared to be an integer. +/// ## Standards-based benefits, alternative documentation @@ -141,11 +153,17 @@ Then create class attributes with fixed values, which will be the available vali {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - Enumerations (or enums) are available in Python since version 3.4. +/// info -!!! tip - If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models. +Enumerations (or enums) are available in Python since version 3.4. + +/// + +/// tip + +If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models. + +/// ### Declare a *path parameter* @@ -181,8 +199,11 @@ You can get the actual value (a `str` in this case) using `model_name.value`, or {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - You could also access the value `"lenet"` with `ModelName.lenet.value`. +/// tip + +You could also access the value `"lenet"` with `ModelName.lenet.value`. + +/// #### Return *enumeration members* @@ -235,10 +256,13 @@ So, you can use it with: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`). +/// tip + +You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`). + +In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`. - In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`. +/// ## Recap diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index da8e53720..ce7d0580d 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Let's take this application as example: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. -!!! note - FastAPI will know that the value of `q` is not required because of the default value `= None`. +/// note - The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. +FastAPI will know that the value of `q` is not required because of the default value `= None`. + +The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. + +/// ## Additional validation @@ -34,30 +41,37 @@ To achieve that, first import: * `Query` from `fastapi` * `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. + +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// - In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. +//// tab | Python 3.8+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. -=== "Python 3.8+" +It will already be installed with FastAPI. + +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. +//// - It will already be installed with FastAPI. +/// info - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. -!!! info - FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0. +If you have an older version, you would get errors when trying to use `Annotated`. - If you have an older version, you would get errors when trying to use `Annotated`. +Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. - Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`. +/// ## Use `Annotated` in the type for the `q` parameter @@ -67,31 +81,39 @@ Now it's the time to use it with FastAPI. 🚀 We had this type annotation: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: str | None = None - ``` +```Python +q: str | None = None +``` -=== "Python 3.8+" +//// - ```Python - q: Union[str, None] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// What we will do is wrap that with `Annotated`, so it becomes: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: Annotated[str | None] = None - ``` +```Python +q: Annotated[str | None] = None +``` -=== "Python 3.8+" +//// - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// Both of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`. @@ -101,25 +123,31 @@ Now let's jump to the fun stuff. 🎉 Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` + +//// Notice that the default value is still `None`, so the parameter is still optional. But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎 -!!! tip +/// tip + +Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. - Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. +/// FastAPI will now: @@ -131,22 +159,29 @@ FastAPI will now: Previous versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you. -!!! tip - For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰 +/// tip + +For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰 + +/// This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI). @@ -176,22 +211,25 @@ q: str | None = None But it declares it explicitly as being a query parameter. -!!! info - Keep in mind that the most important part to make a parameter optional is the part: +/// info - ```Python - = None - ``` +Keep in mind that the most important part to make a parameter optional is the part: - or the: +```Python += None +``` - ```Python - = Query(default=None) - ``` +or the: - as it will use that `None` as the default value, and that way make the parameter **not required**. +```Python += Query(default=None) +``` + +as it will use that `None` as the default value, and that way make the parameter **not required**. + +The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. - The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. +/// Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings: @@ -243,81 +281,113 @@ Because `Annotated` can have more than one metadata annotation, you could now ev You can also add a parameter `min_length`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// ## Add regular expressions You can define a regular expression `pattern` that the parameter should match: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// This specific regular expression pattern checks that the received parameter value: @@ -335,11 +405,13 @@ Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called ` You could still see some code using it: -=== "Python 3.10+ Pydantic v1" +//// tab | Python 3.10+ Pydantic v1 + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} - ``` +//// But know that this is deprecated and it should be updated to use the new parameter `pattern`. 🤓 @@ -349,29 +421,41 @@ You can, of course, use default values other than `None`. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note -!!! note - Having a default value of any type, including `None`, makes the parameter optional (not required). +Having a default value of any type, including `None`, makes the parameter optional (not required). + +/// ## Make it required @@ -389,75 +473,103 @@ q: Union[str, None] = None But we are now declaring it with `Query`, for example like: -=== "Annotated" +//// tab | Annotated - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// -=== "non-Annotated" +//// tab | non-Annotated - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +Still, probably better to use the `Annotated` version. 😉 - !!! tip - Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. +/// - Still, probably better to use the `Annotated` version. 😉 +//// ### Required with Ellipsis (`...`) There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// info -!!! info - If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis". +If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis". - It is used by Pydantic and FastAPI to explicitly declare that a value is required. +It is used by Pydantic and FastAPI to explicitly declare that a value is required. + +/// This will let **FastAPI** know that this parameter is required. @@ -467,47 +579,69 @@ You can declare that a parameter can accept `None`, but that it's still required To do that, you can declare that `None` is a valid type but still use `...` as the default: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +/// -!!! tip - Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` -!!! tip - Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. +//// + +/// tip + +Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. + +/// + +/// tip + +Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. + +/// ## Query parameter list / multiple values @@ -515,50 +649,71 @@ When you define a query parameter explicitly with `Query` you can also declare i For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.9+" +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.9+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Then, with a URL like: @@ -579,8 +734,11 @@ So, the response to that URL would be: } ``` -!!! tip - To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body. +/// tip + +To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body. + +/// The interactive API docs will update accordingly, to allow multiple values: @@ -590,35 +748,49 @@ The interactive API docs will update accordingly, to allow multiple values: And you can also define a default `list` of values if none are provided: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +/// -=== "Python 3.9+ non-Annotated" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +//// If you go to: @@ -641,31 +813,43 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +/// note -!!! note - Keep in mind that in this case, FastAPI won't check the contents of the list. +Keep in mind that in this case, FastAPI won't check the contents of the list. - For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. +For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. + +/// ## Declare more metadata @@ -673,86 +857,121 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. -!!! note - Keep in mind that different tools might have different levels of OpenAPI support. +/// note + +Keep in mind that different tools might have different levels of OpenAPI support. - Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. +Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. + +/// You can add a `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// And a `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// ## Alias parameters @@ -772,41 +991,57 @@ But you still need it to be exactly `item-query`... Then you can declare an `alias`, and that alias is what will be used to find the parameter value: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// ## Deprecating parameters @@ -816,41 +1051,57 @@ You have to leave it there a while because there are clients using it, but you w Then pass the parameter `deprecated=True` to `Query`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// The docs will show it like this: @@ -860,41 +1111,57 @@ The docs will show it like this: To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index bc3b11948..a98ac9b28 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ The parameter values in your function will be: The same way, you can declare optional query parameters, by setting their default to `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// In this case, the function parameter `q` will be optional, and will be `None` by default. -!!! check - Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter. +/// check + +Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter. + +/// ## Query parameter type conversion You can also declare `bool` types, and they will be converted: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// In this case, if you go to: @@ -137,17 +148,21 @@ And you don't have to declare them in any specific order. They will be detected by name: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Required query parameters @@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy And of course, you can define some parameters as required, some as having a default value, and some entirely optional: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// In this case, there are 3 query parameters: @@ -223,5 +242,8 @@ In this case, there are 3 query parameters: * `skip`, an `int` with a default value of `0`. * `limit`, an optional `int`. -!!! tip - You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip + +You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 17ac3b25d..ceaea3626 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ You can define files to be uploaded by the client using `File`. -!!! info - To receive uploaded files, first install `python-multipart`. +/// info - E.g. `pip install python-multipart`. +To receive uploaded files, first install `python-multipart`. - This is because uploaded files are sent as "form data". +E.g. `pip install python-multipart`. + +This is because uploaded files are sent as "form data". + +/// ## Import `File` Import `File` and `UploadFile` from `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## Define `File` Parameters Create file parameters the same way you would for `Body` or `Form`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info -=== "Python 3.8+ non-Annotated" +`File` is a class that inherits directly from `Form`. - !!! tip - Prefer to use the `Annotated` version if possible. +But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes. - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info - `File` is a class that inherits directly from `Form`. +/// tip - But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes. +To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters. -!!! tip - To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters. +/// The files will be uploaded as "form data". @@ -79,26 +106,35 @@ But there are several cases in which you might benefit from using `UploadFile`. Define a file parameter with a type of `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// Using `UploadFile` has several advantages over `bytes`: @@ -141,11 +177,17 @@ If you are inside of a normal `def` *path operation function*, you can access th contents = myfile.file.read() ``` -!!! note "`async` Technical Details" - When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. +/// note | "`async` Technical Details" + +When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. + +/// + +/// note | "Starlette Technical Details" -!!! note "Starlette Technical Details" - **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. +**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. + +/// ## What is "Form Data" @@ -153,82 +195,113 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -!!! note "Technical Details" - Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. +/// note | "Technical Details" + +Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. + +But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body. + +If you want to read more about these encodings and form fields, head to the MDN web docs for POST. + +/// - But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body. +/// warning - If you want to read more about these encodings and form fields, head to the MDN web docs for POST. +You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. -!!! warning - You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Optional File Upload You can make a file optional by using standard type annotations and setting a default value of `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` with Additional Metadata You can also use `File()` with `UploadFile`, for example, to set additional metadata: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Multiple File Uploads @@ -238,76 +311,107 @@ They would be associated to the same "form field" sent using "form data". To use that, declare a list of `bytes` or `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.9+ non-Annotated - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// You will receive, as declared, a `list` of `bytes` or `UploadFile`s. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +You could also use `from starlette.responses import HTMLResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ### Multiple File Uploads with Additional Metadata And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ non-Annotated" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 676ed35ad..9b4342652 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ You can define files and form fields at the same time using `File` and `Form`. -!!! info - To receive uploaded files and/or form data, first install `python-multipart`. +/// info - E.g. `pip install python-multipart`. +To receive uploaded files and/or form data, first install `python-multipart`. + +E.g. `pip install python-multipart`. + +/// ## Import `File` and `Form` -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## Define `File` and `Form` parameters Create file and form parameters the same way you would for `Body` or `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// The files and form fields will be uploaded as form data and you will receive the files and form fields. And you can declare some of the files as `bytes` and some as `UploadFile`. -!!! warning - You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. +/// warning + +You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`. + +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Recap diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 5f8f7b148..88b5b86b6 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ When you need to receive form fields instead of JSON, you can use `Form`. -!!! info - To use forms, first install `python-multipart`. +/// info - E.g. `pip install python-multipart`. +To use forms, first install `python-multipart`. + +E.g. `pip install python-multipart`. + +/// ## Import `Form` Import `Form` from `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## Define `Form` parameters Create form parameters the same way you would for `Body` or `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields. @@ -63,11 +84,17 @@ The spec requires the fields to be exactly na With `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc. -!!! info - `Form` is a class that inherits directly from `Body`. +/// info + +`Form` is a class that inherits directly from `Body`. + +/// + +/// tip -!!! tip - To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters. +To declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters. + +/// ## About "Form Fields" @@ -75,17 +102,23 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -!!! note "Technical Details" - Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. +/// note | "Technical Details" + +Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. + +But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter. + +If you want to read more about these encodings and form fields, head to the MDN web docs for POST. + +/// - But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter. +/// warning - If you want to read more about these encodings and form fields, head to the MDN web docs for POST. +You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`. -!!! warning - You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`. +This is not a limitation of **FastAPI**, it's part of the HTTP protocol. - This is not a limitation of **FastAPI**, it's part of the HTTP protocol. +/// ## Recap diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 75d5df106..8a2dccc81 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ You can declare the type used for the response by annotating the *path operation You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI will use this return type to: @@ -53,35 +59,47 @@ You can use the `response_model` parameter in any of the *path operations*: * `@app.delete()` * etc. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note - Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. +//// + +/// note + +Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. + +/// `response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`. FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration. -!!! tip - If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`. +/// tip + +If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`. + +That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`. - That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`. +/// ### `response_model` Priority @@ -95,37 +113,48 @@ You can also use `response_model=None` to disable creating a response model for Here we are declaring a `UserIn` model, it will contain a plaintext password: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +To use `EmailStr`, first install `email_validator`. -!!! info - To use `EmailStr`, first install `email_validator`. +E.g. `pip install email-validator` +or `pip install pydantic[email]`. - E.g. `pip install email-validator` - or `pip install pydantic[email]`. +/// And we are using this model to declare our input and the same model to declare our output: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Now, whenever a browser is creating a user with a password, the API will return the same password in the response. @@ -133,52 +162,67 @@ In this case, it might not be a problem, because it's the same user sending the But if we use the same model for another *path operation*, we could be sending our user's passwords to every client. -!!! danger - Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing. +/// danger + +Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing. + +/// ## Add an output model We can instead create an input model with the plaintext password and an output model without it: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// Here, even though our *path operation function* is returning the same input user that contains the password: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// ...we declared the `response_model` to be our model `UserOut`, that doesn't include the password: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic). @@ -202,17 +246,21 @@ But in most of the cases where we need to do something like this, we want the mo And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI. @@ -278,17 +326,21 @@ But when you return some other arbitrary object that is not a valid Pydantic typ The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +//// ...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`. @@ -300,17 +352,21 @@ But you might want to still keep the return type annotation in the function to g In this case, you can disable the response model generation by setting `response_model=None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` + +//// This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓 @@ -318,23 +374,29 @@ This will make FastAPI skip the response model generation and that way you can h Your response model could have default values, like: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`. * `tax: float = 10.5` has a default of `10.5`. @@ -348,23 +410,29 @@ For example, if you have models with many optional attributes in a NoSQL databas You can set the *path operation decorator* parameter `response_model_exclude_unset=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// and those default values won't be included in the response, only the values actually set. @@ -377,21 +445,30 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t } ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info + +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + +/// + +/// info + +FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +/// -!!! info - FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. +/// info -!!! info - You can also use: +You can also use: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. +as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. + +/// #### Data with values for fields with defaults @@ -426,10 +503,13 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev So, they will be included in the JSON response. -!!! tip - Notice that the default values can be anything, not only `None`. +/// tip + +Notice that the default values can be anything, not only `None`. + +They can be a list (`[]`), a `float` of `10.5`, etc. - They can be a list (`[]`), a `float` of `10.5`, etc. +/// ### `response_model_include` and `response_model_exclude` @@ -439,45 +519,59 @@ They take a `set` of `str` with the name of the attributes to include (omitting This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output. -!!! tip - But it is still recommended to use the ideas above, using multiple classes, instead of these parameters. +/// tip - This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes. +But it is still recommended to use the ideas above, using multiple classes, instead of these parameters. - This also applies to `response_model_by_alias` that works similarly. +This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes. -=== "Python 3.10+" +This also applies to `response_model_by_alias` that works similarly. - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// -=== "Python 3.8+" +//// tab | Python 3.10+ - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` -!!! tip - The syntax `{"name", "description"}` creates a `set` with those two values. +//// - It is equivalent to `set(["name", "description"])`. +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` + +//// + +/// tip + +The syntax `{"name", "description"}` creates a `set` with those two values. + +It is equivalent to `set(["name", "description"])`. + +/// #### Using `list`s instead of `set`s If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 646378aa1..2613bf73d 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ The same way you can specify a response model, you can also declare the HTTP sta {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. +/// note + +Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. + +/// The `status_code` parameter receives a number with the HTTP status code. -!!! info - `status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`. +/// info + +`status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`. + +/// It will: @@ -27,15 +33,21 @@ It will: -!!! note - Some response codes (see the next section) indicate that the response does not have a body. +/// note + +Some response codes (see the next section) indicate that the response does not have a body. + +FastAPI knows this, and will produce OpenAPI docs that state there is no response body. - FastAPI knows this, and will produce OpenAPI docs that state there is no response body. +/// ## About HTTP status codes -!!! note - If you already know what HTTP status codes are, skip to the next section. +/// note + +If you already know what HTTP status codes are, skip to the next section. + +/// In HTTP, you send a numeric status code of 3 digits as part of the response. @@ -54,8 +66,11 @@ In short: * For generic errors from the client, you can just use `400`. * `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. -!!! tip - To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes. +/// tip + +To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes. + +/// ## Shortcut to remember the names @@ -79,10 +94,13 @@ They are just a convenience, they hold the same number, but that way you can use -!!! note "Technical Details" - You could also use `from starlette import status`. +/// note | "Technical Details" + +You could also use `from starlette import status`. + +**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette. +/// ## Changing the default diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 40231dc0b..141a0bc55 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ Here are several ways to do it. You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs. -=== "Pydantic v2" +//// tab | Pydantic v2 + +In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config. + +You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. - In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config. +//// - You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. +//// tab | Pydantic v1 -=== "Pydantic v1" +In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization. - In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization. +You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. - You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. +//// -!!! tip - You could use the same technique to extend the JSON Schema and add your own custom extra info. +/// tip - For example you could use it to add metadata for a frontend user interface, etc. +You could use the same technique to extend the JSON Schema and add your own custom extra info. -!!! info - OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard. +For example you could use it to add metadata for a frontend user interface, etc. - Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓 +/// - You can read more at the end of this page. +/// info + +OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard. + +Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓 + +You can read more at the end of this page. + +/// ## `Field` additional arguments When using `Field()` with Pydantic models, you can also declare additional `examples`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## `examples` in JSON Schema - OpenAPI @@ -92,41 +114,57 @@ you can also declare a group of `examples` with additional information that will Here we pass `examples` containing one example of the data expected in `Body()`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Example in the docs UI @@ -138,41 +176,57 @@ With any of the methods above it would look like this in the `/docs`: You can of course also pass multiple `examples`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// When you do this, the examples will be part of the internal **JSON Schema** for that body data. @@ -213,41 +267,57 @@ Each specific example `dict` in the `examples` can contain: You can use it like this: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### OpenAPI Examples in the Docs UI @@ -257,17 +327,23 @@ With `openapi_examples` added to `Body()` the `/docs` would look like: ## Technical Details -!!! tip - If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details. +/// tip + +If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details. + +They are more relevant for older versions, before OpenAPI 3.1.0 was available. + +You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓 - They are more relevant for older versions, before OpenAPI 3.1.0 was available. +/// - You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓 +/// warning -!!! warning - These are very technical details about the standards **JSON Schema** and **OpenAPI**. +These are very technical details about the standards **JSON Schema** and **OpenAPI**. - If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them. +If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them. + +/// Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. @@ -285,8 +361,11 @@ OpenAPI also added `example` and `examples` fields to other parts of the specifi * `File()` * `Form()` -!!! info - This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`. +/// info + +This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`. + +/// ### JSON Schema's `examples` field @@ -298,10 +377,13 @@ And now this new `examples` field takes precedence over the old single (and cust This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above). -!!! info - Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉). +/// info + +Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉). + +Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0. - Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0. +/// ### Pydantic and FastAPI `examples` diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index d8682a054..ed427a282 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -20,38 +20,49 @@ Let's first just use the code and see how it works, and then we'll come back to Copy the example in a file `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` +//// ## Run it -!!! info - The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. +/// info - However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: +The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. - `pip install python-multipart` +However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: - This is because **OAuth2** uses "form data" for sending the `username` and `password`. +`pip install python-multipart` + +This is because **OAuth2** uses "form data" for sending the `username` and `password`. + +/// Run the example with: @@ -73,17 +84,23 @@ You will see something like this: -!!! check "Authorize button!" - You already have a shiny new "Authorize" button. +/// check | "Authorize button!" + +You already have a shiny new "Authorize" button. - And your *path operation* has a little lock in the top-right corner that you can click. +And your *path operation* has a little lock in the top-right corner that you can click. + +/// And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields): -!!! note - It doesn't matter what you type in the form, it won't work yet. But we'll get there. +/// note + +It doesn't matter what you type in the form, it won't work yet. But we'll get there. + +/// This is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API. @@ -125,53 +142,71 @@ So, let's review it from that simplified point of view: In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class. -!!! info - A "bearer" token is not the only option. +/// info + +A "bearer" token is not the only option. + +But it's the best one for our use case. - But it's the best one for our use case. +And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. - And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. +In that case, **FastAPI** also provides you with the tools to build it. - In that case, **FastAPI** also provides you with the tools to build it. +/// When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`. -!!! tip - Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`. +Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`. - Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`. +Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. - Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +/// This parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems. We will soon also create the actual path operation. -!!! info - If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`. +/// info + +If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`. + +That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it. - That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it. +/// The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable". @@ -187,35 +222,47 @@ So, it can be used with `Depends`. Now you can pass that `oauth2_scheme` in a dependency with `Depends`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*. **FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs). -!!! info "Technical Details" - **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. +/// info | "Technical Details" + +**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. + +All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI. - All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI. +/// ## What it does diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index dc6d87c9c..6f3bf3944 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -2,26 +2,35 @@ In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// But that is still not that useful. @@ -33,41 +42,57 @@ First, let's create a Pydantic user model. The same way we use Pydantic to declare bodies, we can use it anywhere else: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 13-17" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="5 13-17" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Create a `get_current_user` dependency @@ -79,135 +104,189 @@ Remember that dependencies can have sub-dependencies? The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="26" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="26" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Get the user `get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +```Python hl_lines="20-23 27-28" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20-23 27-28" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// ## Inject the current user So now we can use the same `Depends` with our `get_current_user` in the *path operation*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="32" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="32" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// Notice that we declare the type of `current_user` as the Pydantic model `User`. This will help us inside of the function with all the completion and type checks. -!!! tip - You might remember that request bodies are also declared with Pydantic models. +/// tip - Here **FastAPI** won't get confused because you are using `Depends`. +You might remember that request bodies are also declared with Pydantic models. -!!! check - The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model. +Here **FastAPI** won't get confused because you are using `Depends`. - We are not restricted to having only one dependency that can return that type of data. +/// + +/// check + +The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model. + +We are not restricted to having only one dependency that can return that type of data. + +/// ## Other models @@ -241,41 +320,57 @@ And all of them (or any portion of them that you want) can take the advantage of And all these thousands of *path operations* can be as small as 3 lines: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31-33" +{!> ../../../docs_src/security/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="31-33" - {!> ../../../docs_src/security/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// ## Recap diff --git a/docs/en/docs/tutorial/security/index.md b/docs/en/docs/tutorial/security/index.md index 659a94dc3..d33a2b14d 100644 --- a/docs/en/docs/tutorial/security/index.md +++ b/docs/en/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ It is not very popular or used nowadays. OAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS. -!!! tip - In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt. +/// tip +In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI defines the following security schemes: * This automatic discovery is what is defined in the OpenID Connect specification. -!!! tip - Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy. +/// tip + +Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy. + +The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you. - The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you. +/// ## **FastAPI** utilities diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index b011db67a..52877b916 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -40,10 +40,13 @@ $ pip install pyjwt -!!! info - If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. +/// info - You can read more about it in the PyJWT Installation docs. +If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. + +You can read more about it in the PyJWT Installation docs. + +/// ## Password hashing @@ -79,12 +82,15 @@ $ pip install "passlib[bcrypt]" -!!! tip - With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others. +/// tip + +With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others. - So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database. +So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database. - And your users would be able to login from your Django app or from your **FastAPI** app, at the same time. +And your users would be able to login from your Django app or from your **FastAPI** app, at the same time. + +/// ## Hash and verify the passwords @@ -92,12 +98,15 @@ Import the tools we need from `passlib`. Create a PassLib "context". This is what will be used to hash and verify passwords. -!!! tip - The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc. +/// tip + +The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc. - For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt. +For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt. - And be compatible with all of them at the same time. +And be compatible with all of them at the same time. + +/// Create a utility function to hash a password coming from the user. @@ -105,44 +114,63 @@ And another utility to verify if a received password matches the hash stored. And another one to authenticate and return a user. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 50 57-58 61-62 71-77" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+" +/// - ```Python hl_lines="8 50 57-58 61-62 71-77" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// note - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. -!!! note - If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// ## Handle JWT tokens @@ -172,41 +200,57 @@ Define a Pydantic Model that will be used in the token endpoint for the response Create a utility function to generate a new access token. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 7 14-16 30-32 80-88" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="4 7 14-16 30-32 80-88" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## Update the dependencies @@ -216,41 +260,57 @@ Decode the received token, verify it, and return the current user. If the token is invalid, return an HTTP error right away. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="91-108" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="91-108" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="89-106" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="90-107" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="90-107" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ## Update the `/token` *path operation* @@ -258,41 +318,57 @@ Create a `timedelta` with the expiration time of the token. Create a real JWT access token and return it. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="119-134" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` - ```Python hl_lines="119-134" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="116-131" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="116-131" +{!> ../../../docs_src/security/tutorial004.py!} +``` + +//// ### Technical details about the JWT "subject" `sub` @@ -331,8 +407,11 @@ Using the credentials: Username: `johndoe` Password: `secret` -!!! check - Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version. +/// check + +Notice that nowhere in the code is the plaintext password "`secret`", we only have the hashed version. + +/// @@ -353,8 +432,11 @@ If you open the developer tools, you could see how the data sent only includes t -!!! note - Notice the header `Authorization`, with a value that starts with `Bearer `. +/// note + +Notice the header `Authorization`, with a value that starts with `Bearer `. + +/// ## Advanced usage with `scopes` diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index 6f40531d7..c9f6a1382 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. +/// info - It doesn't matter if it has other characters like `:` or if it is a URL. +In OAuth2 a "scope" is just a string that declares a specific permission required. - Those details are implementation specific. +It doesn't matter if it has other characters like `:` or if it is a URL. - For OAuth2 they are just strings. +Those details are implementation specific. + +For OAuth2 they are just strings. + +/// ## Code to get the `username` and `password` @@ -49,41 +52,57 @@ Now let's use the utilities provided by **FastAPI** to handle this. First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 78" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="4 79" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// `OAuth2PasswordRequestForm` is a class dependency that declares a form body with: @@ -92,29 +111,38 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe * An optional `scope` field as a big string, composed of strings separated by spaces. * An optional `grant_type`. -!!! tip - The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it. +/// tip + +The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it. - If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`. +If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`. + +/// * An optional `client_id` (we don't need it for our example). * An optional `client_secret` (we don't need it for our example). -!!! info - The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`. +/// info + +The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI. - `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI. +But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly. - But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly. +But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier. - But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier. +/// ### Use the form data -!!! tip - The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent. +/// tip + +The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent. + +We are not using `scopes` in this example, but the functionality is there if you need it. - We are not using `scopes` in this example, but the functionality is there if you need it. +/// Now, get the user data from the (fake) database, using the `username` from the form field. @@ -122,41 +150,57 @@ If there is no such user, we return an error saying "Incorrect username or passw For the error, we use the exception `HTTPException`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 79-81" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="3 79-81" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 80-82" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="3 80-82" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +/// + +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// ### Check the password @@ -182,41 +226,57 @@ If your database is stolen, the thief won't have your users' plaintext passwords So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="83-86" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="82-85" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="83-86" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// #### About `**user_dict` @@ -234,8 +294,11 @@ UserInDB( ) ``` -!!! info - For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// info + +For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// ## Return the token @@ -247,55 +310,77 @@ And it should have an `access_token`, with a string containing our access token. For this simple example, we are going to just be completely insecure and return the same `username` as the token. -!!! tip - In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens. +/// tip + +In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens. + +But for now, let's focus on the specific details we need. - But for now, let's focus on the specific details we need. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="87" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` - ```Python hl_lines="87" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="88" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +```Python hl_lines="88" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` -!!! tip - By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example. +//// - This is something that you have to do yourself in your code, and make sure you use those JSON keys. +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` - It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications. +//// - For the rest, **FastAPI** handles it for you. +/// tip + +By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example. + +This is something that you have to do yourself in your code, and make sure you use those JSON keys. + +It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications. + +For the rest, **FastAPI** handles it for you. + +/// ## Update the dependencies @@ -309,56 +394,75 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py310.py!} - ``` +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="58-66 69-74 94" - {!> ../../../docs_src/security/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="58-66 69-74 94" +{!> ../../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../../docs_src/security/tutorial003_an.py!} +``` - ```Python hl_lines="59-67 70-75 95" - {!> ../../../docs_src/security/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="56-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec. -!!! info - The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec. +Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header. - Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header. +In the case of bearer tokens (our case), the value of that header should be `Bearer`. - In the case of bearer tokens (our case), the value of that header should be `Bearer`. +You can actually skip that extra header and it would still work. - You can actually skip that extra header and it would still work. +But it's provided here to be compliant with the specifications. - But it's provided here to be compliant with the specifications. +Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future. - Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future. +That's the benefit of standards... - That's the benefit of standards... +/// ## See it in action diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 1f0ebc08b..0645cc9f1 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -1,11 +1,14 @@ # SQL (Relational) Databases -!!! info - These docs are about to be updated. 🎉 +/// info - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +These docs are about to be updated. 🎉 - The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. +The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. + +The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. + +/// **FastAPI** doesn't require you to use a SQL (relational) database. @@ -25,13 +28,19 @@ In this example, we'll use **SQLite**, because it uses a single file and Python Later, for your production application, you might want to use a database server like **PostgreSQL**. -!!! tip - There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql +/// tip + +There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql + +/// -!!! note - Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. +/// note - The **FastAPI** specific code is as small as always. +Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. + +The **FastAPI** specific code is as small as always. + +/// ## ORMs @@ -65,8 +74,11 @@ Here we will see how to work with **SQLAlchemy ORM**. In a similar way you could use any other ORM. -!!! tip - There's an equivalent article using Peewee here in the docs. +/// tip + +There's an equivalent article using Peewee here in the docs. + +/// ## File structure @@ -131,9 +143,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other). -!!! tip +/// tip + +This is the main line that you would have to modify if you wanted to use a different database. - This is the main line that you would have to modify if you wanted to use a different database. +/// ### Create the SQLAlchemy `engine` @@ -155,15 +169,17 @@ connect_args={"check_same_thread": False} ...is needed only for `SQLite`. It's not needed for other databases. -!!! info "Technical Details" +/// info | "Technical Details" + +By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. - By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. +This is to prevent accidentally sharing the same connection for different things (for different requests). - This is to prevent accidentally sharing the same connection for different things (for different requests). +But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. - But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. +Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. - Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. +/// ### Create a `SessionLocal` class @@ -199,10 +215,13 @@ Let's now see the file `sql_app/models.py`. We will use this `Base` class we created before to create the SQLAlchemy models. -!!! tip - SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. +/// tip - But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. +SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. + +But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. + +/// Import `Base` from `database` (the file `database.py` from above). @@ -252,12 +271,15 @@ And when accessing the attribute `owner` in an `Item`, it will contain a `User` Now let's check the file `sql_app/schemas.py`. -!!! tip - To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. +/// tip + +To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. - These Pydantic models define more or less a "schema" (a valid data shape). +These Pydantic models define more or less a "schema" (a valid data shape). - So this will help us avoiding confusion while using both. +So this will help us avoiding confusion while using both. + +/// ### Create initial Pydantic *models* / schemas @@ -269,23 +291,29 @@ So, the user will also have a `password` when creating it. But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// #### SQLAlchemy style and Pydantic style @@ -313,26 +341,35 @@ The same way, when reading a user, we can now declare that `items` will contain Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. -!!! tip - Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. +/// ### Use Pydantic's `orm_mode` @@ -342,32 +379,41 @@ This ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ -!!! tip - Notice it's assigning a value with `=`, like: +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - `orm_mode = True` +//// - It doesn't use `:` as for the type declarations before. +/// tip - This is setting a config value, not declaring a type. +Notice it's assigning a value with `=`, like: + +`orm_mode = True` + +It doesn't use `:` as for the type declarations before. + +This is setting a config value, not declaring a type. + +/// Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes). @@ -433,8 +479,11 @@ Create utility functions to: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add unit tests for them. +/// tip + +By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add unit tests for them. + +/// ### Create data @@ -451,39 +500,51 @@ The steps are: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. +/// info - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. -!!! tip - The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. +The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. +/// - And then pass the `hashed_password` argument with the value to save. +/// tip -!!! warning - This example is not secure, the password is not hashed. +The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. - In a real life application you would need to hash the password and never save them in plaintext. +But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. - For more details, go back to the Security section in the tutorial. +And then pass the `hashed_password` argument with the value to save. - Here we are focusing only on the tools and mechanics of databases. +/// -!!! tip - Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: +/// warning - `item.dict()` +This example is not secure, the password is not hashed. - and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: +In a real life application you would need to hash the password and never save them in plaintext. - `Item(**item.dict())` +For more details, go back to the Security section in the tutorial. - And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: +Here we are focusing only on the tools and mechanics of databases. - `Item(**item.dict(), owner_id=user_id)` +/// + +/// tip + +Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: + +`item.dict()` + +and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: + +`Item(**item.dict())` + +And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## Main **FastAPI** app @@ -493,17 +554,21 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part In a very simplistic way create the database tables: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// #### Alembic Note @@ -527,63 +592,81 @@ For that, we will create a new dependency with `yield`, as explained before in t Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -!!! info - We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. +/// info - And then we close it in the `finally` block. +We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. +And then we close it in the `finally` block. - But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} +This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. + +But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} + +/// And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy. This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ -!!! info "Technical Details" - The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +/// info | "Technical Details" - But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. +The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. + +But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. + +/// ### Create your **FastAPI** *path operations* Now, finally, here's the standard **FastAPI** *path operations* code. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards. @@ -591,15 +674,21 @@ And then we can create the required dependency in the *path operation function*, With that, we can just call `crud.get_user` directly from inside of the *path operation function* and use that session. -!!! tip - Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. +/// tip + +Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. + +But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. + +/// - But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. +/// tip -!!! tip - Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. +Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. - But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. +But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. + +/// ### About `def` vs `async def` @@ -628,11 +717,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. +/// info + +If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. + +/// -!!! note "Very Technical Details" - If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. +/// note | "Very Technical Details" + +If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. + +/// ## Migrations @@ -666,23 +761,29 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// * `sql_app/crud.py`: @@ -692,25 +793,31 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// ## Check it You can copy this code and use it as is. -!!! info +/// info + +In fact, the code shown here is part of the tests. As most of the code in these docs. - In fact, the code shown here is part of the tests. As most of the code in these docs. +/// Then you can run it with Uvicorn: @@ -751,24 +858,31 @@ A "middleware" is basically a function that is always executed for each request, The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. -!!! info - We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. +And then we close it in the `finally` block. - And then we close it in the `finally` block. +This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. +/// ### About `request.state` @@ -789,10 +903,16 @@ Adding a **middleware** here is similar to what a dependency with `yield` does, * So, a connection will be created for every request. * Even when the *path operation* that handles that request didn't need the DB. -!!! tip - It's probably better to use dependencies with `yield` when they are enough for the use case. +/// tip + +It's probably better to use dependencies with `yield` when they are enough for the use case. + +/// + +/// info + +Dependencies with `yield` were added recently to **FastAPI**. -!!! info - Dependencies with `yield` were added recently to **FastAPI**. +A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. - A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. +/// diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 311d2b1c8..b8ce3b551 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ You can serve static files automatically from a directory using `StaticFiles`. {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Technical Details" - You could also use `from starlette.staticfiles import StaticFiles`. +/// note | "Technical Details" - **FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette. +You could also use `from starlette.staticfiles import StaticFiles`. + +**FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette. + +/// ### What is "Mounting" diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 8d199a4c7..95c8c5bef 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -8,10 +8,13 @@ With it, you can use `httpx`. +/// info - E.g. `pip install httpx`. +To use `TestClient`, first install `httpx`. + +E.g. `pip install httpx`. + +/// Import `TestClient`. @@ -27,20 +30,29 @@ Write simple `assert` statements with the standard Python expressions that you n {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip - Notice that the testing functions are normal `def`, not `async def`. +/// tip + +Notice that the testing functions are normal `def`, not `async def`. + +And the calls to the client are also normal calls, not using `await`. + +This allows you to use `pytest` directly without complications. + +/// + +/// note | "Technical Details" + +You could also use `from starlette.testclient import TestClient`. - And the calls to the client are also normal calls, not using `await`. +**FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette. - This allows you to use `pytest` directly without complications. +/// -!!! note "Technical Details" - You could also use `from starlette.testclient import TestClient`. +/// tip - **FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette. +If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial. -!!! tip - If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} in the advanced tutorial. +/// ## Separating tests @@ -110,41 +122,57 @@ It has a `POST` operation that could return several errors. Both *path operations* require an `X-Token` header. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Extended testing file @@ -168,10 +196,13 @@ E.g.: For more information about how to pass data to the backend (using `httpx` or the `TestClient`) check the HTTPX documentation. -!!! info - Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models. +/// info + +Note that the `TestClient` receives data that can be converted to JSON, not Pydantic models. + +If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. - If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. +/// ## Run it diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index d204974b8..18c6d3f53 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -5,3 +5,8 @@ plugins: cards_layout_options: logo: ../en/docs/img/icon-white.svg typeset: +markdown_extensions: + material.extensions.preview: + targets: + include: + - ./* diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index c13e36798..782d4ef87 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -6,6 +6,10 @@ theme: name: material custom_dir: ../en/overrides palette: + - media: "(prefers-color-scheme)" + toggle: + icon: material/lightbulb-auto + name: Switch to light mode - media: '(prefers-color-scheme: light)' scheme: default primary: teal @@ -19,18 +23,30 @@ theme: accent: amber toggle: icon: material/lightbulb-outline - name: Switch to light mode + name: Switch to system preference features: - - search.suggest - - search.highlight + - content.code.annotate + - content.code.copy + # - content.code.select + - content.footnote.tooltips - content.tabs.link - - navigation.indexes - content.tooltips + - navigation.footer + - navigation.indexes + - navigation.instant + - navigation.instant.prefetch + - navigation.instant.preview + - navigation.instant.progress - navigation.path - - content.code.annotate - - content.code.copy - - content.code.select - navigation.tabs + - navigation.tabs.sticky + - navigation.top + - navigation.tracking + - search.highlight + - search.share + - search.suggest + - toc.follow + icon: repo: fontawesome/brands/github-alt logo: img/icon-white.svg @@ -38,9 +54,11 @@ theme: language: en repo_name: fastapi/fastapi repo_url: https://github.com/fastapi/fastapi -edit_uri: '' plugins: - search: null + # Material for MkDocs + search: + social: + # Other plugins macros: include_yaml: - external_links: ../en/data/external_links.yml @@ -81,6 +99,7 @@ plugins: signature_crossrefs: true show_symbol_type_heading: true show_symbol_type_toc: true + nav: - FastAPI: - index.md @@ -233,30 +252,72 @@ nav: - benchmarks.md - management.md - release-notes.md + markdown_extensions: + # Python Markdown + abbr: + attr_list: + footnotes: + md_in_html: + tables: toc: permalink: true - markdown.extensions.codehilite: - guess_lang: false - mdx_include: - base_path: docs - admonition: null - codehilite: null - extra: null + + # Python Markdown Extensions + pymdownx.betterem: + smart_enable: all + pymdownx.caret: + pymdownx.highlight: + line_spans: __span + pymdownx.inlinehilite: + pymdownx.keys: + pymdownx.mark: pymdownx.superfences: custom_fences: - name: mermaid class: mermaid - format: !!python/name:pymdownx.superfences.fence_code_format '' - pymdownx.tabbed: - alternate_style: true - pymdownx.tilde: null - attr_list: null - md_in_html: null + format: !!python/name:pymdownx.superfences.fence_code_format + pymdownx.tilde: + + # pymdownx blocks + pymdownx.blocks.admonition: + types: + - note + - attention + - caution + - danger + - error + - tip + - hint + - warning + # Custom types + - info + - check + pymdownx.blocks.details: + pymdownx.blocks.tab: + alternate_style: True + + # Other extensions + mdx_include: + base_path: docs + extra: analytics: provider: google property: G-YNEVN69SC3 + feedback: + title: Was this page helpful? + ratings: + - icon: material/emoticon-happy-outline + name: This page was helpful + data: 1 + note: >- + Thanks for your feedback! + - icon: material/emoticon-sad-outline + name: This page could be improved + data: 0 + note: >- + Thanks for your feedback! social: - icon: fontawesome/brands/github-alt link: https://github.com/fastapi/fastapi @@ -272,6 +333,7 @@ extra: link: https://medium.com/@tiangolo - icon: fontawesome/solid/globe link: https://tiangolo.com + alternate: - link: / name: en - English @@ -321,11 +383,14 @@ extra: name: zh-hant - 繁體中文 - link: /em/ name: 😉 + extra_css: - css/termynal.css - css/custom.css + extra_javascript: - js/termynal.js - js/custom.js + hooks: - ../../scripts/mkdocs_hooks.py diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index eaa3369eb..f40fad03c 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "Advertencia" - Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. +/// warning | "Advertencia" - No será serializado con el modelo, etc. +Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. - Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). +No será serializado con el modelo, etc. -!!! note "Detalles Técnicos" - También podrías utilizar `from starlette.responses import JSONResponse`. +Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). - **FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`. +/// + +/// note | "Detalles Técnicos" + +También podrías utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`. + +/// ## OpenAPI y documentación de API diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index eb8fe5c1b..88ef8e19f 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -6,10 +6,13 @@ El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_bl En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. -!!! tip - Las próximas secciones **no son necesariamente "avanzadas"**. +/// tip - Y es posible que para tu caso, la solución se encuentre en una de estas. +Las próximas secciones **no son necesariamente "avanzadas"**. + +Y es posible que para tu caso, la solución se encuentre en una de estas. + +/// ## Lee primero el Tutorial diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index e4edcc52b..9e8714fe4 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "Advertencia" - Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. +/// warning | "Advertencia" + +Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. + +/// Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`. @@ -23,13 +26,19 @@ Deberías hacerlo después de adicionar todas tus *operaciones de path*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Consejo" - Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. +/// tip | "Consejo" + +Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. + +/// + +/// warning | "Advertencia" + +Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. -!!! warning "Advertencia" - Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. +Incluso si están en diferentes módulos (archivos Python). - Incluso si están en diferentes módulos (archivos Python). +/// ## Excluir de OpenAPI diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index dee44ac08..7ce5bddca 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizado De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. -!!! tip "Consejo" - `JSONResponse` en sí misma es una subclase de `Response`. +/// tip | "Consejo" + +`JSONResponse` en sí misma es una subclase de `Response`. + +/// Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. @@ -35,10 +38,13 @@ Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos ante {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Detalles Técnicos" - También puedes usar `from starlette.responses import JSONResponse`. +/// note | "Detalles Técnicos" + +También puedes usar `from starlette.responses import JSONResponse`. + +**FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. - **FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. +/// ## Devolviendo una `Response` personalizada diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index aec88a584..414b145fc 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -29,13 +29,16 @@ Crea un response tal como se describe en [Retornar una respuesta directamente](r {!../../../docs_src/response_headers/tutorial001.py!} ``` -!!! note "Detalles Técnicos" - También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. +/// note | "Detalles Técnicos" - **FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. +También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. +**FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. - Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. + +Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. + +/// ## Headers Personalizados diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 139e8f9bd..7fa8047e9 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -4,10 +4,13 @@ Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - Las siguientes secciones **no necesariamente son "avanzadas"**. +/// tip - Y es posible que para tu caso de uso, la solución esté en alguna de ellas. +Las siguientes secciones **no necesariamente son "avanzadas"**. + +Y es posible que para tu caso de uso, la solución esté en alguna de ellas. + +/// ## Leer primero el Tutorial diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 18159775d..193d24270 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "Nota" - Solo puedes usar `await` dentro de funciones creadas con `async def`. +/// note | "Nota" + +Solo puedes usar `await` dentro de funciones creadas con `async def`. + +/// --- @@ -135,8 +138,11 @@ Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. illustration -!!! info - Las ilustraciones fueron creados por Ketrina Thompson. 🎨 +/// info + +Las ilustraciones fueron creados por Ketrina Thompson. 🎨 + +/// --- @@ -198,8 +204,11 @@ Sólo las comes y listo 🍔 ⏹. No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. -!!! info - Las ilustraciones fueron creados por Ketrina Thompson. 🎨 +/// info + +Las ilustraciones fueron creados por Ketrina Thompson. 🎨 + +/// --- @@ -387,12 +396,15 @@ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que te ## Detalles muy técnicos -!!! warning "Advertencia" - Probablemente puedas saltarte esto. +/// warning | "Advertencia" + +Probablemente puedas saltarte esto. + +Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel. - Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel. +Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa. - Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa. +/// ### Path operation functions diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index d8719d6bd..7d09a2739 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -42,8 +42,11 @@ Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por deba FastAPI también sigue la convención de que cualquier cambio hecho en una "PATCH" version es para solucionar errores y *non-breaking changes*. -!!! tip - El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. +/// tip + +El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. + +/// Entonces, deberías fijar la versión así: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 En versiones "MINOR" son añadidas nuevas características y posibles breaking changes. -!!! tip - La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. +/// tip + +La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. + +/// ## Actualizando las versiones de FastAPI diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md index 481f72e9e..8163349ab 100644 --- a/docs/es/docs/external-links.md +++ b/docs/es/docs/external-links.md @@ -6,8 +6,11 @@ Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con Aquí hay una lista incompleta de algunos de ellos. -!!! tip "Consejo" - Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un Pull Request agregándolo. +/// tip | "Consejo" + +Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un Pull Request agregándolo. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index d957b10b7..3c610f8f1 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` significa: +/// info - Pasa las keys y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` significa: + +Pasa las keys y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Soporte del editor diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index 1138af76a..d75af7d81 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -4,12 +4,15 @@ Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar c Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. -!!! tip - **GraphQL** resuelve algunos casos de uso específicos. +/// tip - Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. +**GraphQL** resuelve algunos casos de uso específicos. - Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 +Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. + +Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 + +/// ## Librerías GraphQL @@ -46,8 +49,11 @@ Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a starlette-graphene3, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** -!!! tip - Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. +/// tip + +Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. + +/// ## Aprende más diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 89edbb31e..fce434483 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,8 +12,11 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -!!! note "Nota" - Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. +/// note | "Nota" + +Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. + +/// ## Motivación @@ -253,8 +256,11 @@ Tomado de la documentación oficial de Pydantic: {!../../../docs_src/python_types/tutorial010.py!} ``` -!!! info "Información" - Para aprender más sobre Pydantic mira su documentación. +/// info | "Información" + +Para aprender más sobre Pydantic mira su documentación. + +/// **FastAPI** está todo basado en Pydantic. @@ -282,5 +288,8 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -!!! info "Información" - Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. +/// info | "Información" + +Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. + +/// diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 9f736575d..27ba8ed57 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Puedes definir parámetros de Cookie de la misma manera que defines parámetros Primero importa `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Declarar parámetros de `Cookie` @@ -48,49 +64,71 @@ Luego declara los parámetros de cookie usando la misma estructura que con `Path El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Detalles Técnicos" -=== "Python 3.8+ non-Annotated" +`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. - !!! tip - Prefer to use the `Annotated` version if possible. +Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Detalles Técnicos" - `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. +/// info - Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. +Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. -!!! info - Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. +/// ## Resumen diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index c37ce00fb..affdfebff 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "Nota" - El comando `uvicorn main:app` se refiere a: +/// note | "Nota" - * `main`: el archivo `main.py` (el "módulo" de Python). - * `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. - * `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. +El comando `uvicorn main:app` se refiere a: + +* `main`: el archivo `main.py` (el "módulo" de Python). +* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. +* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. + +/// En el output, hay una línea que dice más o menos: @@ -136,10 +139,13 @@ También podrías usarlo para generar código automáticamente, para los cliente `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -!!! note "Detalles Técnicos" - `FastAPI` es una clase que hereda directamente de `Starlette`. +/// note | "Detalles Técnicos" + +`FastAPI` es una clase que hereda directamente de `Starlette`. - También puedes usar toda la funcionalidad de Starlette. +También puedes usar toda la funcionalidad de Starlette. + +/// ### Paso 2: crea un "instance" de `FastAPI` @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Información" - Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". +/// info | "Información" + +Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". + +/// Cuando construyes una API, el "path" es la manera principal de separar los "intereses" y los "recursos". @@ -250,16 +259,19 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una operación get -!!! info "Información sobre `@decorator`" - Esa sintaxis `@algo` se llama un "decorador" en Python. +/// info | "Información sobre `@decorator`" - Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). +Esa sintaxis `@algo` se llama un "decorador" en Python. - Un "decorador" toma la función que tiene debajo y hace algo con ella. +Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). - En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. +Un "decorador" toma la función que tiene debajo y hace algo con ella. - Es el "**decorador de operaciones de path**". +En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. + +Es el "**decorador de operaciones de path**". + +/// También puedes usar las otras operaciones: @@ -274,14 +286,17 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -!!! tip "Consejo" - Tienes la libertad de usar cada operación (método de HTTP) como quieras. +/// tip | "Consejo" + +Tienes la libertad de usar cada operación (método de HTTP) como quieras. - **FastAPI** no impone ningún significado específico. +**FastAPI** no impone ningún significado específico. - La información que está presentada aquí es una guía, no un requerimiento. +La información que está presentada aquí es una guía, no un requerimiento. - Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. +Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. + +/// ### Paso 4: define la **función de la operación de path** @@ -309,8 +324,11 @@ También podrías definirla como una función estándar en lugar de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Nota" - Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. +/// note | "Nota" + +Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. + +/// ### Paso 5: devuelve el contenido diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index f11820ef2..46c57c4c3 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -50,22 +50,25 @@ $ pip install "fastapi[all]" ...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. -!!! note "Nota" - También puedes instalarlo parte por parte. +/// note | "Nota" - Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: +También puedes instalarlo parte por parte. - ``` - pip install fastapi - ``` +Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: - También debes instalar `uvicorn` para que funcione como tu servidor: +``` +pip install fastapi +``` + +También debes instalar `uvicorn` para que funcione como tu servidor: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. - Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. +/// ## Guía Avanzada de Usuario diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 7faa92f51..73bd586f1 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. -!!! check "Revisa" - Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. +/// check | "Revisa" + +Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. + +/// ## Conversión de datos @@ -35,10 +38,13 @@ Si corres este ejemplo y abres tu navegador en "parsing"
automático del request. - Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request. +/// ## Validación de datos @@ -63,12 +69,15 @@ debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2 -!!! check "Revisa" - Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. +/// check | "Revisa" - Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. +Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. - Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. +Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. + +Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. + +/// ## Documentación @@ -76,10 +85,13 @@ Cuando abras tu navegador en -!!! check "Revisa" - Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) +/// check | "Revisa" + +Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) + +Observa que el parámetro de path está declarado como un integer. - Observa que el parámetro de path está declarado como un integer. +/// ## Beneficios basados en estándares, documentación alternativa @@ -131,11 +143,17 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Información" - Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. +/// info | "Información" -!!! tip "Consejo" - Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. +Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. + +/// + +/// tip | "Consejo" + +Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. + +/// ### Declara un *parámetro de path* @@ -171,8 +189,11 @@ Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value` {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Consejo" - También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. +/// tip | "Consejo" + +También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. + +/// #### Devuelve *enumeration members* @@ -225,10 +246,13 @@ Entonces lo puedes usar con: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Consejo" - Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). +/// tip | "Consejo" + +Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). + +En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. - En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. +/// ## Repaso diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 76dc331a9..52a3e66a4 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -69,13 +69,19 @@ Del mismo modo puedes declarar parámetros de query opcionales definiendo el val En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -!!! check "Revisa" - También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. +/// check | "Revisa" -!!! note "Nota" - FastAPI sabrá que `q` es opcional por el `= None`. +También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. - El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. +/// + +/// note | "Nota" + +FastAPI sabrá que `q` es opcional por el `= None`. + +El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. + +/// ## Conversión de tipos de parámetros de query @@ -193,5 +199,8 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -!!! tip "Consejo" - También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. +/// tip | "Consejo" + +También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md index 58c34b7fc..a5ab1597e 100644 --- a/docs/fa/docs/features.md +++ b/docs/fa/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` یعنی: +/// info - کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` یعنی: + +کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### پشتیبانی ویرایشگر diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md index c5752a4b5..e3ee5fcbc 100644 --- a/docs/fa/docs/tutorial/middleware.md +++ b/docs/fa/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. * سپس **پاسخ** را برمی گرداند. -!!! توجه "جزئیات فنی" - در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. +/// توجه | "جزئیات فنی" - در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. +در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. + +در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. + +/// ## ساخت یک میان افزار @@ -31,14 +34,19 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. +/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. + +اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. + +/// + +/// توجه | "جزئیات فنی" - اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. +شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. -!!! توجه "جزئیات فنی" - شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. +**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. - **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. +/// ### قبل و بعد از `پاسخ` diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md index 4e68ba961..c0827a8b3 100644 --- a/docs/fa/docs/tutorial/security/index.md +++ b/docs/fa/docs/tutorial/security/index.md @@ -33,8 +33,11 @@ پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود. -!!! نکته - در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. +/// نکته + +در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. + +/// ## استاندارد OpenID Connect @@ -86,10 +89,13 @@ * شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف داده‌های احراز هویت OAuth2 به صورت خودکار. * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص می‌کند. -!!! نکته - ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. +/// نکته + +ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. + +مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. - مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. +/// ## ابزارهای **FastAPI** diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 685a054ad..44bbf50f8 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Réponses supplémentaires dans OpenAPI -!!! warning "Attention" - Ceci concerne un sujet plutôt avancé. +/// warning | "Attention" - Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. +Ceci concerne un sujet plutôt avancé. + +Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. + +/// Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc. @@ -27,20 +30,26 @@ Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un mod {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Remarque" - Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. +/// note | "Remarque" + +Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. + +/// + +/// info -!!! info - La clé `model` ne fait pas partie d'OpenAPI. +La clé `model` ne fait pas partie d'OpenAPI. - **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. +**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. - Le bon endroit est : +Le bon endroit est : - * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : - * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : - * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. - * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. +* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : + * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : + * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. + * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. + +/// Les réponses générées au format OpenAPI pour cette *opération de chemin* seront : @@ -172,13 +181,19 @@ Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Remarque" - Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. +/// note | "Remarque" + +Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. + +/// + +/// info + +À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). -!!! info - À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). +Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. - Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. +/// ## Combinaison d'informations diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index 51f0db737..46db2e0b6 100644 --- a/docs/fr/docs/advanced/additional-status-codes.md +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "Attention" - Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. +/// warning | "Attention" - Elle ne sera pas sérialisée avec un modèle. +Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. - Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). +Elle ne sera pas sérialisée avec un modèle. -!!! note "Détails techniques" - Vous pouvez également utiliser `from starlette.responses import JSONResponse`. +Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). - Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. +/// + +/// note | "Détails techniques" + +Vous pouvez également utiliser `from starlette.responses import JSONResponse`. + +Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. + +/// ## Documents OpenAPI et API diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index 4599bcb6f..198fa8c30 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -6,10 +6,13 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. -!!! note "Remarque" - Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. +/// note | "Remarque" - Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. +Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. + +Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. + +/// ## Lisez d'abord le didacticiel diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 77f551aea..4727020ae 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## ID d'opération OpenAPI -!!! warning "Attention" - Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. +/// warning | "Attention" + +Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. + +/// Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`. @@ -23,13 +26,19 @@ Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Astuce" - Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. +/// tip | "Astuce" + +Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. + +/// + +/// warning | "Attention" + +Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. -!!! warning "Attention" - Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. +Même s'ils se trouvent dans des modules différents (fichiers Python). - Même s'ils se trouvent dans des modules différents (fichiers Python). +/// ## Exclusion d'OpenAPI @@ -65,8 +74,11 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI. -!!! note "Détails techniques" - La spécification OpenAPI appelle ces métadonnées des Objets d'opération. +/// note | "Détails techniques" + +La spécification OpenAPI appelle ces métadonnées des Objets d'opération. + +/// Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation. @@ -74,8 +86,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -!!! tip "Astuce" - Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. +/// tip | "Astuce" + +Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`. @@ -162,7 +177,10 @@ Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le {!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` -!!! tip "Astuce" - Ici, nous réutilisons le même modèle Pydantic. +/// tip | "Astuce" + +Ici, nous réutilisons le même modèle Pydantic. + +Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. - Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. +/// diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index ed29446d4..49ca32230 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -!!! note "Remarque" - `JSONResponse` est elle-même une sous-classe de `Response`. +/// note | "Remarque" + +`JSONResponse` est elle-même une sous-classe de `Response`. + +/// Et quand vous retournez une `Response`, **FastAPI** la transmet directement. @@ -35,10 +38,13 @@ Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convert {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Détails techniques" - Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. +/// note | "Détails techniques" + +Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. + +**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. - **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. +/// ## Renvoyer une `Response` personnalisée diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index a64edd671..059a60b69 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -37,12 +37,18 @@ Il est utilisé par de nombreuses entreprises, dont Mozilla, Red Hat et Eventbri Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des premières idées qui a inspiré "la recherche de" **FastAPI**. -!!! note +/// note + Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Avoir une interface de documentation automatique de l'API. +/// + ### Flask Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django. @@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver. Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires. Proposer un système de routage simple et facile à utiliser. +/// + ### Requests **FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent. @@ -98,9 +107,13 @@ def read_url(): Notez les similitudes entre `requests.get(...)` et `@app.get(...)`. -!!! check "A inspiré **FastAPI** à" -_ Avoir une API simple et intuitive. -_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. +/// check | "A inspiré **FastAPI** à" + +Avoir une API simple et intuitive. + +Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. + +/// ### Swagger / OpenAPI @@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI". -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé. - Intégrer des outils d'interface utilisateur basés sur des normes : +Intégrer des outils d'interface utilisateur basés sur des normes : - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). +Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). + +/// ### Frameworks REST pour Flask @@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation. +/// + ### Webargs Une autre grande fonctionnalité requise par les API est le APISpec Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins. @@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète. -!!! info +/// info + APISpec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Supporter la norme ouverte pour les API, OpenAPI. +/// + ### Flask-apispec C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec. @@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent : Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}. -!!! info +/// info + Flask-apispec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. +/// + ### NestJS (et Angular) Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular. @@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. - Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. +Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. + +/// ### Sanic C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask. -!!! note "Détails techniques" +/// note | "Détails techniques" + Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. - Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. +Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. + +/// + +/// check | "A inspiré **FastAPI** à" -!!! check "A inspiré **FastAPI** à" Trouvez un moyen d'avoir une performance folle. - C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). +C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). + +/// ### Falcon @@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Trouver des moyens d'obtenir de bonnes performances. - Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. +Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. + +Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. - Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. +/// ### Molten @@ -294,10 +343,13 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -!!! check "A inspiré **FastAPI** à" +/// check | "A inspiré **FastAPI** à" + Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. - Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). +Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). + +/// ### Hug @@ -314,16 +366,22 @@ API et des CLI. Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant. -!!! info +/// info + Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | "A inspiré **FastAPI** à" + Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar. - Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python - pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. +Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python +pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. + +Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. - Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. +/// ### APIStar (<= 0.5) @@ -351,23 +409,29 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web. -!!! info +/// info + APIStar a été créé par Tom Christie. Le même gars qui a créé : - * Django REST Framework - * Starlette (sur lequel **FastAPI** est basé) - * Uvicorn (utilisé par Starlette et **FastAPI**) +* Django REST Framework +* Starlette (sur lequel **FastAPI** est basé) +* Uvicorn (utilisé par Starlette et **FastAPI**) + +/// + +/// check | "A inspiré **FastAPI** à" -!!! check "A inspiré **FastAPI** à" Exister. - L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. +L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. - Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. +Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. - Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. +Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. - Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. +Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. + +/// ## Utilisés par **FastAPI** @@ -380,10 +444,13 @@ Cela le rend extrêmement intuitif. Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est basé sur les mêmes type hints Python, le support de l'éditeur est grand. -!!! check "**FastAPI** l'utilise pour" +/// check | "**FastAPI** l'utilise pour" + Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON). - **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. +**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. + +/// ### Starlette @@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc. -!!! note "Détails techniques" +/// note | "Détails techniques" + ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire. - Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. +Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. + +/// + +/// check | "**FastAPI** l'utilise pour" -!!! check "**FastAPI** l'utilise pour" Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus. - La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. +La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. - Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. +Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. + +/// ### Uvicorn @@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de C'est le serveur recommandé pour Starlette et **FastAPI**. -!!! check "**FastAPI** le recommande comme" +/// check | "**FastAPI** le recommande comme" + Le serveur web principal pour exécuter les applications **FastAPI**. - Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. +Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. + +Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. - Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks et vitesse diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index eabd9686a..0f8f34e65 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -20,8 +20,11 @@ async def read_results(): return results ``` -!!! note - Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. +/// note + +Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. + +/// --- @@ -135,8 +138,11 @@ Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨. -!!! info - Illustrations proposées par Ketrina Thompson. 🎨 +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// --- @@ -198,8 +204,11 @@ Vous les mangez, et vous avez terminé 🍔 ⏹. Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞. -!!! info - Illustrations proposées par Ketrina Thompson. 🎨 +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// --- @@ -384,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e ## Détails très techniques -!!! warning "Attention !" - Vous pouvez probablement ignorer cela. +/// warning | "Attention !" + +Vous pouvez probablement ignorer cela. + +Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. - Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. +Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. - Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. +/// ### Fonctions de chemin diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md index ed4d32f5a..408958339 100644 --- a/docs/fr/docs/contributing.md +++ b/docs/fr/docs/contributing.md @@ -24,72 +24,85 @@ Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez Activez le nouvel environnement avec : -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// - Ou si vous utilisez Bash pour Windows (par exemple Git Bash): +//// tab | Windows Bash -
+Ou si vous utilisez Bash pour Windows (par exemple Git Bash): - ```console - $ source ./env/Scripts/activate - ``` +
-
+```console +$ source ./env/Scripts/activate +``` + +
+ +//// Pour vérifier que cela a fonctionné, utilisez : -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which pip -
+some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +
- some/directory/fastapi/env/bin/pip - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +
-
+//// Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 -!!! tip - Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. +/// tip - Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. +Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. + +Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. + +/// ### Flit @@ -111,31 +124,35 @@ Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "fl Et maintenant, utilisez `flit` pour installer les dépendances de développement : -=== "Linux, macOS" +//// tab | Linux, macOS + +
+ +```console +$ flit install --deps develop --symlink -
+---> 100% +``` - ```console - $ flit install --deps develop --symlink +
- ---> 100% - ``` +//// -
+//// tab | Windows -=== "Windows" +Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : +
-
+```console +$ flit install --deps develop --pth-file - ```console - $ flit install --deps develop --pth-file +---> 100% +``` - ---> 100% - ``` +
-
+//// Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. @@ -185,8 +202,11 @@ La documentation utilise pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. -!!! tip - Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. +/// tip + +Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. + +Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. - Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. +/// * Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. @@ -296,8 +319,11 @@ Disons que vous voulez traduire une page pour une langue qui a déjà des traduc Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. -!!! tip - La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". +/// tip + +La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". + +/// Maintenant, lancez le serveur en live pour les documents en espagnol : @@ -334,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. +/// tip + +Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. + +/// * Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à @@ -406,10 +435,13 @@ Updating en Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. -!!! tip - Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. +/// tip + +Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. + +Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 +/// Commencez par traduire la page principale, `docs/ht/index.md`. diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md index d2dcae722..0f3b64700 100644 --- a/docs/fr/docs/deployment/docker.md +++ b/docs/fr/docs/deployment/docker.md @@ -17,8 +17,11 @@ Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suff Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration. -!!! tip "Astuce" - Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. +/// tip | "Astuce" + +Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. + +/// ## Créer un `Dockerfile` diff --git a/docs/fr/docs/deployment/https.md b/docs/fr/docs/deployment/https.md index ccf1f847a..3f7068ff0 100644 --- a/docs/fr/docs/deployment/https.md +++ b/docs/fr/docs/deployment/https.md @@ -4,8 +4,11 @@ Il est facile de penser que HTTPS peut simplement être "activé" ou non. Mais c'est beaucoup plus complexe que cela. -!!! tip - Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. +/// tip + +Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. + +/// Pour apprendre les bases du HTTPS, du point de vue d'un utilisateur, consultez https://howhttps.works/. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index eb1253cf8..6a737fdef 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -25,75 +25,89 @@ Lorsqu'on se réfère à la machine distante, il est courant de l'appeler **serv Vous pouvez installer un serveur compatible ASGI avec : -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. +* Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip | "Astuce" -
+En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. - !!! tip "Astuce" - En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. +Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. - Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. +/// -=== "Hypercorn" +//// - * Hypercorn, un serveur ASGI également compatible avec HTTP/2. +//// tab | Hypercorn -
+* Hypercorn, un serveur ASGI également compatible avec HTTP/2. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+...ou tout autre serveur ASGI. - ...ou tout autre serveur ASGI. +//// ## Exécutez le programme serveur Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple : -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. -!!! warning - N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. + L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. - L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. + Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. - Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. +/// ## Hypercorn avec Trio diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 136165e9d..8ea79a172 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,8 +48,11 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -!!! tip "Astuce" - Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. +/// tip | "Astuce" + +Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. + +/// Donc, vous devriez être capable d'épingler une version comme suit : @@ -59,8 +62,11 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -!!! tip "Astuce" - Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. +/// tip | "Astuce" + +Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. + +/// ## Mise à jour des versions FastAPI diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md index 2f928f523..91a9eae58 100644 --- a/docs/fr/docs/external-links.md +++ b/docs/fr/docs/external-links.md @@ -6,8 +6,11 @@ Il existe de nombreux articles, outils et projets liés à **FastAPI**. Voici une liste incomplète de certains d'entre eux. -!!! tip "Astuce" - Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant. +/// tip | "Astuce" + +Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 1457df2a5..afb1de243 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` signifie: +/// info - Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` signifie: + +Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Support d'éditeurs diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 4232633e3..e3c99e0a9 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -13,8 +13,11 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières. -!!! note - Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. +/// note + +Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. + +/// ## Motivations @@ -174,10 +177,13 @@ Les listes étant un type contenant des types internes, mettez ces derniers entr {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Astuce" - Ces types internes entre crochets sont appelés des "paramètres de type". +/// tip | "Astuce" + +Ces types internes entre crochets sont appelés des "paramètres de type". + +Ici, `str` est un paramètre de type passé à `List`. - Ici, `str` est un paramètre de type passé à `List`. +/// Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`. @@ -281,8 +287,11 @@ Extrait de la documentation officielle de **Pydantic** : {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. +/// info + +Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. + +/// **FastAPI** est basé entièrement sur **Pydantic**. @@ -310,5 +319,8 @@ Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous. -!!! info - Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. +/// info + +Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. + +/// diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md index 563b601f0..fd8e5d688 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip -!!! note - Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note + +Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +/// ## Paramètres multiples du body @@ -62,17 +81,21 @@ Dans l'exemple précédent, les opérations de routage attendaient un body JSON Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). @@ -93,8 +116,11 @@ Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevo } ``` -!!! note - "Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. +/// note + +"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +/// **FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. @@ -109,41 +135,57 @@ Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// Dans ce cas, **FastAPI** s'attendra à un body semblable à : @@ -183,44 +225,63 @@ q: str | None = None Par exemple : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +//// -!!! info - `Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. +/// info + +`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +/// ## Inclure un paramètre imbriqué dans le body @@ -236,41 +297,57 @@ item: Item = Body(embed=True) Voici un exemple complet : -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// Dans ce cas **FastAPI** attendra un body semblable à : diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index ae952405c..9a5121f10 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -8,12 +8,15 @@ Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un cli Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. -!!! info - Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. +/// info - Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. +Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. - Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. +Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. + +Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. + +/// ## Importez le `BaseModel` de Pydantic @@ -110,16 +113,19 @@ Mais vous auriez le même support de l'éditeur avec -!!! tip "Astuce" - Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. +/// tip | "Astuce" + +Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. - Ce qui améliore le support pour les modèles Pydantic avec : +Ce qui améliore le support pour les modèles Pydantic avec : - * de l'auto-complétion - * des vérifications de type - * du "refactoring" (ou remaniement de code) - * de la recherche - * de l'inspection +* de l'auto-complétion +* des vérifications de type +* du "refactoring" (ou remaniement de code) +* de la recherche +* de l'inspection + +/// ## Utilisez le modèle @@ -155,10 +161,13 @@ Les paramètres de la fonction seront reconnus comme tel : * Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**. * Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. + +Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. - Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. +/// ## Sans Pydantic diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index e58872d30..bcd780a82 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -74,9 +74,12 @@ Ainsi, la ligne : ne sera pas exécutée. -!!! info +/// info + Pour plus d'informations, consultez la documentation officielle de Python. +/// + ## Exécutez votre code avec votre débogueur Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e98283f1e..bf476d990 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note - La commande `uvicorn main:app` fait référence à : +/// note - * `main` : le fichier `main.py` (le module Python). - * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. - * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! +La commande `uvicorn main:app` fait référence à : + +* `main` : le fichier `main.py` (le module Python). +* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. +* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! + +/// Vous devriez voir dans la console, une ligne semblable à la suivante : @@ -137,10 +140,13 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. -!!! note "Détails techniques" - `FastAPI` est une classe héritant directement de `Starlette`. +/// note | "Détails techniques" + +`FastAPI` est une classe héritant directement de `Starlette`. - Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. +Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. + +/// ### Étape 2 : créer une "instance" `FastAPI` @@ -200,9 +206,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// info + +Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// #### Opération @@ -251,16 +259,19 @@ Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de * le chemin `/` * en utilisant une opération get -!!! info "`@décorateur` Info" - Cette syntaxe `@something` en Python est appelée un "décorateur". +/// info | "`@décorateur` Info" + +Cette syntaxe `@something` en Python est appelée un "décorateur". - Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). +Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). - Un "décorateur" prend la fonction en dessous et en fait quelque chose. +Un "décorateur" prend la fonction en dessous et en fait quelque chose. - Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. +Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. - C'est le "**décorateur d'opération de chemin**". +C'est le "**décorateur d'opération de chemin**". + +/// Vous pouvez aussi utiliser les autres opérations : @@ -275,14 +286,17 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -!!! tip "Astuce" - Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. +/// tip | "Astuce" + +Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. + +**FastAPI** n'impose pas de sens spécifique à chacune d'elle. - **FastAPI** n'impose pas de sens spécifique à chacune d'elle. +Les informations qui sont présentées ici forment une directive générale, pas des obligations. - Les informations qui sont présentées ici forment une directive générale, pas des obligations. +Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. - Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. +/// ### Étape 4 : définir la **fonction de chemin**. @@ -310,8 +324,11 @@ Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `as {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. +/// note + +Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. + +/// ### Étape 5 : retourner le contenu diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md index 4dc202b33..83cc5f9e8 100644 --- a/docs/fr/docs/tutorial/index.md +++ b/docs/fr/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install fastapi[all] ... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code. -!!! note - Vous pouvez également l'installer pièce par pièce. +/// note - C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : +Vous pouvez également l'installer pièce par pièce. - ``` - pip install fastapi - ``` +C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : - Installez également `uvicorn` pour qu'il fonctionne comme serveur : +``` +pip install fastapi +``` + +Installez également `uvicorn` pour qu'il fonctionne comme serveur : + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. - Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. +/// ## Guide utilisateur avancé diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md index e8dcd37fb..eedd59f91 100644 --- a/docs/fr/docs/tutorial/path-params-numeric-validations.md +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ De la même façon que vous pouvez déclarer plus de validations et de métadonn Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+" +/// - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// info - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. -!!! info - FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. +Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. - Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. +Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. - Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. +/// ## Déclarer des métadonnées @@ -55,49 +74,71 @@ Vous pouvez déclarer les mêmes paramètres que pour `Query`. Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -!!! note - Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. + +/// ## Ordonnez les paramètres comme vous le souhaitez -!!! tip - Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis. @@ -113,33 +154,45 @@ Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par le Ainsi, vous pouvez déclarer votre fonction comme suit : -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. - !!! tip - Préférez utiliser la version `Annotated` si possible. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +//// ## Ordonnez les paramètres comme vous le souhaitez (astuces) -!!! tip - Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin. @@ -164,17 +217,21 @@ Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Validations numériques : supérieur ou égal @@ -182,26 +239,35 @@ Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez décl Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Validations numériques : supérieur ou égal et inférieur ou égal @@ -210,26 +276,35 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +Préférez utiliser la version `Annotated` si possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Préférez utiliser la version `Annotated` si possible. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +//// ## Validations numériques : supérieur et inférieur ou égal @@ -238,26 +313,35 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Préférez utiliser la version `Annotated` si possible. +Préférez utiliser la version `Annotated` si possible. - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Validations numériques : flottants, supérieur et inférieur @@ -269,26 +353,35 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. Et la même chose pour lt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` - !!! tip - Préférez utiliser la version `Annotated` si possible. +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip + +Préférez utiliser la version `Annotated` si possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Pour résumer @@ -301,18 +394,24 @@ Et vous pouvez également déclarer des validations numériques : * `lt` : `l`ess `t`han * `le` : `l`ess than or `e`qual -!!! info - `Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. +/// info + +`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. + +Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. + +/// + +/// note | "Détails techniques" - Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. +Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. -!!! note "Détails techniques" - Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. +Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. - Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. +Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. - Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. +Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. - Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. +De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. - De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. +/// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 523e2c8c2..94c36a20d 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -28,9 +28,12 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti Ici, `item_id` est déclaré comme `int`. -!!! check "vérifier" - Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles - que des vérifications d'erreur, de l'auto-complétion, etc. +/// check | "vérifier" + +Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles +que des vérifications d'erreur, de l'auto-complétion, etc. + +/// ## Conversion de données @@ -40,12 +43,15 @@ Si vous exécutez cet exemple et allez sur "parsing"
automatique. - Grâce aux déclarations de types, **FastAPI** fournit du - "parsing" automatique. +/// ## Validation de données @@ -72,12 +78,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u http://127.0.0.1:8000/items/4.2. -!!! check "vérifier" - Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. +/// check | "vérifier" - Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. +Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. - Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. +Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. + +Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. + +/// ## Documentation @@ -86,10 +95,13 @@ documentation générée automatiquement et interactive : -!!! info - À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). +/// info + +À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). + +On voit bien dans la documentation que `item_id` est déclaré comme entier. - On voit bien dans la documentation que `item_id` est déclaré comme entier. +/// ## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative. @@ -141,11 +153,17 @@ Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les va {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info - Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. +/// info -!!! tip "Astuce" - Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. +Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. + +/// + +/// tip | "Astuce" + +Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. + +/// ### Déclarer un paramètre de chemin @@ -181,8 +199,11 @@ Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici) {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Astuce" - Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. +/// tip | "Astuce" + +Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. + +/// #### Retourner des *membres d'énumération* @@ -235,10 +256,13 @@ Vous pouvez donc l'utilisez comme tel : {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Astuce" - Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). +/// tip | "Astuce" + +Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). + +Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. - Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. +/// ## Récapitulatif diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index f5248fe8b..63578ec40 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ Commençons avec cette application pour exemple : Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. +/// note - Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. + +Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +/// ## Validation additionnelle @@ -51,22 +54,25 @@ q: Union[str, None] = None Mais déclare explicitement `q` comme étant un paramètre de requête. -!!! info - Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : +/// info - ```Python - = None - ``` +Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : - ou : +```Python += None +``` - ```Python - = Query(None) - ``` +ou : - et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. +```Python += Query(None) +``` + +et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. - Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. +Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. + +/// Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : @@ -112,8 +118,11 @@ Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "Rappel" - Avoir une valeur par défaut rend le paramètre optionnel. +/// note | "Rappel" + +Avoir une valeur par défaut rend le paramètre optionnel. + +/// ## Rendre ce paramètre requis @@ -141,8 +150,11 @@ Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info - Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". +/// info + +Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". + +/// Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. @@ -175,8 +187,11 @@ Donc la réponse de cette URL serait : } ``` -!!! tip "Astuce" - Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. +/// tip | "Astuce" + +Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +/// La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : @@ -217,10 +232,13 @@ Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. +/// note - Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. +Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + +Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +/// ## Déclarer des métadonnées supplémentaires @@ -228,10 +246,13 @@ On peut aussi ajouter plus d'informations sur le paramètre. Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. -!!! note - Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. +/// note + +Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + +Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. - Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. +/// Vous pouvez ajouter un `title` : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 962135f63..b9f1540c9 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -69,14 +69,19 @@ De la même façon, vous pouvez définir des paramètres de requête comme optio Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -!!! check "Remarque" - On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. +/// check | "Remarque" -!!! note - **FastAPI** saura que `q` est optionnel grâce au `=None`. +On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. - Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. +/// +/// note + +**FastAPI** saura que `q` est optionnel grâce au `=None`. + +Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. + +/// ## Conversion des types des paramètres de requête @@ -194,5 +199,8 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -!!! tip "Astuce" - Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. +/// tip | "Astuce" + +Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. + +/// diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index b7231ad56..e605bbb55 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -376,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**: * Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. * Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. -* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). * a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index 6b6de24f0..f0dee3d73 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -!!! note "Catatan" - Kamu juga dapat meng-installnya bagian demi bagian. +/// note | "Catatan" - Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: +Kamu juga dapat meng-installnya bagian demi bagian. - ``` - pip install fastapi - ``` +Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: - Juga install `uvicorn` untuk menjalankan server" +``` +pip install fastapi +``` + +Juga install `uvicorn` untuk menjalankan server" + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. - Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. +/// ## Pedoman Pengguna Lanjutan diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 38f611734..272f9a37e 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -1,4 +1,3 @@ - {!../../../docs/missing-translation.md!} diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index d1f8e6451..622affa6e 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "注意" - 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 +/// warning | "注意" - モデルなどはシリアライズされません。 +上記の例のように `Response` を明示的に返す場合、それは直接返されます。 - 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 +モデルなどはシリアライズされません。 -!!! note "技術詳細" - `from starlette.responses import JSONResponse` を利用することもできます。 +必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 - **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 +/// + +/// note | "技術詳細" + +`from starlette.responses import JSONResponse` を利用することもできます。 + +**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 + +/// ## OpenAPIとAPIドキュメント diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index d8b47629a..a7ce6b54d 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -!!! note "備考" - メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 +/// note | "備考" + +メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 + +/// ## `ORJSONResponse` を使う @@ -25,15 +28,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 +/// info | "情報" + +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 + +この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 + +そして、OpenAPIにはそのようにドキュメントされます。 + +/// - この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 +/// tip | "豆知識" - そして、OpenAPIにはそのようにドキュメントされます。 +`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 -!!! tip "豆知識" - `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 +/// ## HTMLレスポンス @@ -46,12 +55,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 +/// info | "情報" - この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 - そして、OpenAPIにはそのようにドキュメント化されます。 +この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 + +そして、OpenAPIにはそのようにドキュメント化されます。 + +/// ### `Response` を返す @@ -63,11 +75,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "注意" - *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 +/// warning | "注意" + +*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 + +/// + +/// info | "情報" -!!! info "情報" - もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 +もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 + +/// ### OpenAPIドキュメントと `Response` のオーバーライド @@ -97,10 +115,13 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -!!! note "技術詳細" - `from starlette.responses import HTMLResponse` も利用できます。 +/// note | "技術詳細" + +`from starlette.responses import HTMLResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `Response` @@ -147,15 +168,21 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 `ujson`を使った、代替のJSONレスポンスです。 -!!! warning "注意" - `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 +/// warning | "注意" + +`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "豆知識" - `ORJSONResponse` のほうが高速な代替かもしれません。 +/// tip | "豆知識" + +`ORJSONResponse` のほうが高速な代替かもしれません。 + +/// ### `RedirectResponse` @@ -183,8 +210,11 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "豆知識" - ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 +/// tip | "豆知識" + +ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 + +/// ### `FileResponse` @@ -215,8 +245,11 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "豆知識" - 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 +/// tip | "豆知識" + +前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 + +/// ## その他のドキュメント diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index 2d60e7489..da3c2a2bf 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -6,10 +6,13 @@ 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -!!! tip "豆知識" - 以降のセクションは、 **必ずしも"応用編"ではありません**。 +/// tip | "豆知識" - ユースケースによっては、その中から解決策を見つけられるかもしれません。 +以降のセクションは、 **必ずしも"応用編"ではありません**。 + +ユースケースによっては、その中から解決策を見つけられるかもしれません。 + +/// ## 先にチュートリアルを読む diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 35b381cae..ae60126cb 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI operationId -!!! warning "注意" - あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 +/// warning | "注意" + +あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 + +/// *path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。 @@ -23,13 +26,19 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "豆知識" - `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 +/// tip | "豆知識" + +`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 + +/// + +/// warning | "注意" + +この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 -!!! warning "注意" - この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 +それらが異なるモジュール (Pythonファイル) にあるとしてもです。 - それらが異なるモジュール (Pythonファイル) にあるとしてもです。 +/// ## OpenAPIから除外する diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 10ec88548..5c25471b1 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -!!! tip "豆知識" - `JSONResponse` それ自体は、 `Response` のサブクラスです。 +/// tip | "豆知識" + +`JSONResponse` それ自体は、 `Response` のサブクラスです。 + +/// `Response` を返した場合は、**FastAPI** は直接それを返します。 @@ -35,10 +38,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import JSONResponse` も利用できます。 +/// note | "技術詳細" + +また、`from starlette.responses import JSONResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ## カスタム `Response` を返す diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 65e4112a6..615f9d17c 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -50,10 +50,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.websockets import WebSocket` を使用しても構いません. +/// note | "技術詳細" - **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 +`from starlette.websockets import WebSocket` を使用しても構いません. + +**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 + +/// ## メッセージの送受信 @@ -116,12 +119,15 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート {!../../../docs_src/websockets/tutorial002.py!} ``` -!!! info "情報" - WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 +/// info | "情報" + +WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 + +クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 - クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 +将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 - 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 +/// ### 依存関係を用いてWebSocketsを試してみる @@ -144,8 +150,11 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -!!! tip "豆知識" - クエリ `token` は依存パッケージによって処理されることに注意してください。 +/// tip | "豆知識" + +クエリ `token` は依存パッケージによって処理されることに注意してください。 + +/// これにより、WebSocketに接続してメッセージを送受信できます。 @@ -171,12 +180,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -!!! tip "豆知識" - 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 +/// tip | "豆知識" + +上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 + +しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 - しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 +もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 - もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 +/// ## その他のドキュメント diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ce4b36408..343ae4ed8 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -!!! note "備考" - Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 +/// note | "備考" -!!! check "**FastAPI**へ与えたインスピレーション" - 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 +Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 + +/// ### Flask @@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -!!! check "**FastAPI**へ与えたインスピレーション" - マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 - シンプルで簡単なルーティングの仕組みを持っている点。 +シンプルで簡単なルーティングの仕組みを持っている点。 +/// ### Requests @@ -90,11 +98,13 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -!!! check "**FastAPI**へ与えたインスピレーション" - * シンプルで直感的なAPIを持っている点。 - * HTTPメソッド名を直接利用し、単純で直感的である。 - * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// check | "**FastAPI**へ与えたインスピレーション" + +* シンプルで直感的なAPIを持っている点。 +* HTTPメソッド名を直接利用し、単純で直感的である。 +* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// ### Swagger / OpenAPI @@ -108,15 +118,18 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 +/// check | "**FastAPI**へ与えたインスピレーション" - そして、標準に基づくユーザーインターフェースツールを統合しています。 +独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 - * Swagger UI - * ReDoc +そして、標準に基づくユーザーインターフェースツールを統合しています。 - この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 +* Swagger UI +* ReDoc + +この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 + +/// ### Flask REST フレームワーク @@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -!!! check "**FastAPI**へ与えたインスピレーション" - コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 + +/// ### Webargs @@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -!!! info "情報" - Webargsは、Marshmallowと同じ開発者により作られました。 +/// info | "情報" + +Webargsは、Marshmallowと同じ開発者により作られました。 + +/// -!!! check "**FastAPI**へ与えたインスピレーション" - 受信したデータに対する自動的なバリデーションを持っている点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +受信したデータに対する自動的なバリデーションを持っている点。 + +/// ### APISpec @@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -!!! info "情報" - APISpecは、Marshmallowと同じ開発者により作成されました。 +/// info | "情報" + +APISpecは、Marshmallowと同じ開発者により作成されました。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +OpenAPIという、APIについてのオープンな標準をサポートしている点。 -!!! check "**FastAPI**へ与えたインスピレーション" - OpenAPIという、APIについてのオープンな標準をサポートしている点。 +/// ### Flask-apispec @@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -!!! info "情報" - Flask-apispecはMarshmallowと同じ開発者により作成されました。 +/// info | "情報" -!!! check "**FastAPI**へ与えたインスピレーション" - シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 +Flask-apispecはMarshmallowと同じ開発者により作成されました。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 + +/// ### NestJS (とAngular) @@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 + +強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 - 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 +/// ### Sanic `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -!!! note "技術詳細" - Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 +/// note | "技術詳細" - `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 +Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 物凄い性能を出す方法を見つけた点。 +`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 - **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +物凄い性能を出す方法を見つけた点。 + +**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 + +/// ### Falcon @@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしい性能を得るための方法を見つけた点。 +/// check | "**FastAPI**へ与えたインスピレーション" + +素晴らしい性能を得るための方法を見つけた点。 + +Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 - Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 +**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 - **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 +/// ### Molten @@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -!!! check "**FastAPI**へ与えたインスピレーション" - モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 +/// check | "**FastAPI**へ与えたインスピレーション" - 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) +モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 + +同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) + +/// ### Hug @@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -!!! info "情報" - HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 +/// info | "情報" + +HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 + +/// + +/// check | "**FastAPI**へ与えたインスピレーション" + +HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 -!!! check "**FastAPI**へ与えたインスピレーション" - HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 +Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 - Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 +Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 - Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 +/// ### APIStar (<= 0.5) @@ -322,23 +377,29 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -!!! info "情報" - APIStarはTom Christieにより開発されました。以下の開発者でもあります: +/// info | "情報" - * Django REST Framework - * Starlette (**FastAPI**のベースになっています) - * Uvicorn (Starletteや**FastAPI**で利用されています) +APIStarはTom Christieにより開発されました。以下の開発者でもあります: -!!! check "**FastAPI**へ与えたインスピレーション" - 存在そのもの。 +* Django REST Framework +* Starlette (**FastAPI**のベースになっています) +* Uvicorn (Starletteや**FastAPI**で利用されています) - 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 +/// - そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 +/// check | "**FastAPI**へ与えたインスピレーション" - その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 +存在そのもの。 - 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 +複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 + +そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 + +その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 + +私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 + +/// ## **FastAPI**が利用しているもの @@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -!!! check "**FastAPI**での使用用途" - データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 +/// check | "**FastAPI**での使用用途" + +データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 + +**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 - **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 +/// ### Starlette @@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -!!! note "技術詳細" - ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 +/// note | "技術詳細" - しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 +ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 -!!! check "**FastAPI**での使用用途" - webに関するコアな部分を全て扱います。その上に機能を追加します。 +しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 - `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 +/// - 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 +/// check | "**FastAPI**での使用用途" + +webに関するコアな部分を全て扱います。その上に機能を追加します。 + +`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 + +基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 + +/// ### Uvicorn @@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -!!! check "**FastAPI**が推奨する理由" - **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 +/// check | "**FastAPI**が推奨する理由" + +**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 + +Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 - Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 +詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 - 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 +/// ## ベンチマーク と スピード diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 5e38d1cec..ce9dac56f 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "備考" - `async def` を使用して作成された関数の内部でしか `await` は使用できません。 +/// note | "備考" + +`async def` を使用して作成された関数の内部でしか `await` は使用できません。 + +/// --- @@ -355,12 +358,15 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -!!! warning "注意" - 恐らくスキップしても良いでしょう。 +/// warning | "注意" + +恐らくスキップしても良いでしょう。 + +この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 - この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 +かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 - かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 +/// ### Path operation 関数 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md index be8e9280e..86926b213 100644 --- a/docs/ja/docs/contributing.md +++ b/docs/ja/docs/contributing.md @@ -24,71 +24,84 @@ $ python -m venv env 新しい環境を有効化するには: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
- もしwindows用のBash (例えば、Git Bash)を使っているなら: +//// -
+//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +もしwindows用のBash (例えば、Git Bash)を使っているなら: -
+
+ +```console +$ source ./env/Scripts/activate +``` + +
+ +//// 動作の確認には、下記を実行します: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip -
+some/directory/fastapi/env/bin/pip +``` + +
+ +//// `env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 -!!! tip "豆知識" - この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 +/// tip | "豆知識" + +この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 +これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 + +/// ### pip @@ -152,8 +165,11 @@ $ bash scripts/format-imports.sh そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 -!!! tip "豆知識" - `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 +/// tip | "豆知識" + +`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 + +/// すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 @@ -238,10 +254,13 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 * あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 -!!! tip "豆知識" - すでにあるプルリクエストに修正提案つきのコメントを追加できます。 +/// tip | "豆知識" + +すでにあるプルリクエストに修正提案つきのコメントを追加できます。 + +修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 - 修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 +/// * issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 @@ -263,8 +282,11 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 -!!! tip "豆知識" - メイン (「公式」) 言語は英語で、`docs/en/`にあります。 +/// tip | "豆知識" + +メイン (「公式」) 言語は英語で、`docs/en/`にあります。 + +/// 次に、ドキュメントのライブサーバーをスペイン語で実行します: @@ -301,8 +323,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "豆知識" - パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 +/// tip | "豆知識" + +パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 + +/// * ここで、英語のMkDocs構成ファイルを開きます: @@ -373,10 +398,13 @@ Updating en これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 -!!! tip "豆知識" - 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 +/// tip | "豆知識" + +翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 + +そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 +/// まず、メインページの`docs/ht/index.md`を翻訳します。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index abe4f2c66..c6b21fd1b 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -151,10 +151,13 @@ FastAPIでWeb APIを構築する際に、コードにエラーがある場合、 しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 -!!! tip - ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 +/// tip - そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 +...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 + +そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 + +/// あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。 @@ -243,11 +246,14 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * **クラウド・サービス**によるレプリケーション * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 -!!! tip - これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 - +/// tip + +これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 + + +コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. - コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. +/// ## 開始前の事前のステップ @@ -265,10 +271,13 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 -!!! tip - また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 +/// tip - その場合は、このようなことを心配する必要はないです。🤷 +また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 + +その場合は、このようなことを心配する必要はないです。🤷 + +/// ### 事前ステップの戦略例 @@ -280,9 +289,12 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * 事前のステップを実行し、アプリケーションを起動するbashスクリプト * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 -!!! tip - - コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. +/// tip + + +コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. + +/// ## リソースの利用 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index 0c9df648d..c294ef88d 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -6,9 +6,12 @@ FastAPIアプリケーションをデプロイする場合、一般的なアプ Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。 -!!! tip - TODO: なぜか遷移できない - お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 +/// tip + +TODO: なぜか遷移できない +お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 + +///
Dockerfile プレビュー 👀 @@ -139,10 +142,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 +/// info + +パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 - Poetryを使った例は、後述するセクションでご紹介します。👇 +Poetryを使った例は、後述するセクションでご紹介します。👇 + +/// ### **FastAPI**コードを作成する @@ -230,8 +236,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。 -!!! tip - コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 +/// tip + +コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 + +/// これで、次のようなディレクトリ構造になるはずです: @@ -305,10 +314,13 @@ $ docker build -t myimage . -!!! tip - 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 +/// tip + +末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 + +この場合、同じカレント・ディレクトリ(`.`)です。 - この場合、同じカレント・ディレクトリ(`.`)です。 +/// ### Dockerコンテナの起動する @@ -405,8 +417,11 @@ FastAPI アプリケーションの **コンテナ・イメージ**(および 例えばTraefikのように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。 -!!! tip - TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 +/// tip + +TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 + +/// あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。 @@ -434,8 +449,11 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。 -!!! tip -  HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 +/// tip + +HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 + +/// そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。 @@ -520,8 +538,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ 複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 -!!! info - もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 +/// info + +もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 + +/// ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。 @@ -537,8 +558,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 +/// warning + +このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 + +/// このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。 @@ -546,8 +570,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ また、スクリプトで**開始前の事前ステップ**を実行することもサポートしている。 -!!! tip - すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi +/// tip + +すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi + +/// ### 公式Dockerイメージのプロセス数 @@ -672,8 +699,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします 10. app` ディレクトリを `/code` ディレクトリにコピーします 11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します -!!! tip - "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます +/// tip + +"+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます + +/// **Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index a291f870f..ac40b0982 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -4,8 +4,11 @@ HTTPSは単に「有効」か「無効」かで決まるものだと思いがち しかし、それよりもはるかに複雑です。 -!!! tip - もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 +/// tip + +もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 + +/// 利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: https://howhttps.works/. @@ -75,8 +78,11 @@ DNSサーバーでは、**取得したドメイン**をあなたのサーバー これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。 -!!! tip - ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 +/// tip + +ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 + +/// ### DNS @@ -124,8 +130,11 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 -!!! tip - 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 +/// tip + +通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 + +/// ### HTTPS リクエスト diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 449aea31e..c17e63728 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -4,66 +4,77 @@ 以下の様なASGI対応のサーバをインストールする必要があります: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 +* Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
-!!! tip "豆知識" - `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 +//// - これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 +/// tip | "豆知識" -=== "Hypercorn" +`standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 - * Hypercorn, HTTP/2にも対応しているASGIサーバ。 +これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 -
+/// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* Hypercorn, HTTP/2にも対応しているASGIサーバ。 -
+
- ...または、これら以外のASGIサーバ。 +```console +$ pip install hypercorn + +---> 100% +``` + +
+ +...または、これら以外のASGIサーバ。 + +//// そして、チュートリアルと同様な方法でアプリケーションを起動して下さい。ただし、以下の様に`--reload` オプションは使用しないで下さい: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -
+INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +
- INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// -
+//// tab | Hypercorn -=== "Hypercorn" +
-
+```console +$ hypercorn main:app --bind 0.0.0.0:80 - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +
-
+//// 停止した場合に自動的に再起動させるツールを設定したいかもしれません。 diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index 51d0bc2d4..38ceab017 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -17,11 +17,14 @@ ここでは**Gunicorn**が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 -!!! info - - DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} +/// info - 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} + +特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +/// ## GunicornによるUvicornのワーカー・プロセスの管理 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 03cccb3f3..941ddb71b 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,8 +42,11 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -!!! tip "豆知識" - 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 +/// tip | "豆知識" + +「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 + +/// 従って、以下の様なバージョンの固定が望ましいです: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -!!! tip "豆知識" - 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 +/// tip | "豆知識" + +「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 + +/// ## FastAPIのバージョンのアップグレード diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md index 4cd15c8aa..65cebc8d2 100644 --- a/docs/ja/docs/external-links.md +++ b/docs/ja/docs/external-links.md @@ -6,8 +6,11 @@ それらの不完全なリストを以下に示します。 -!!! tip "豆知識" - ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 +/// tip | "豆知識" + +ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 98c59e7c4..73c0192c7 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "情報" - `**second_user_data` は以下を意味します: +/// info | "情報" - `second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 +`**second_user_data` は以下を意味します: + +`second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 + +/// ### エディタのサポート diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index f8e02fdc3..730a209ab 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -12,8 +12,11 @@ しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 -!!! note "備考" - もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 +/// note | "備考" + +もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +/// ## 動機 @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "豆知識" - 角括弧内の内部の型は「型パラメータ」と呼ばれています。 +/// tip | "豆知識" + +角括弧内の内部の型は「型パラメータ」と呼ばれています。 + +この場合、`str`は`List`に渡される型パラメータです。 - この場合、`str`は`List`に渡される型パラメータです。 +/// つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 @@ -282,8 +288,11 @@ Pydanticの公式ドキュメントから引用: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "情報" - Pydanticについてより学びたい方はドキュメントを参照してください. +/// info | "情報" + +Pydanticについてより学びたい方はドキュメントを参照してください. + +/// **FastAPI** はすべてPydanticをベースにしています。 @@ -311,5 +320,8 @@ Pydanticの公式ドキュメントから引用: 重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 -!!! info "情報" - すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください +/// info | "情報" + +すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください + +/// diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 8f01e8216..b9f6d694b 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -10,8 +10,11 @@ {!../../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "注意" - `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 +/// warning | "注意" + +`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +/// ## モデルの属性の宣言 @@ -23,17 +26,23 @@ `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 -!!! note "技術詳細" - 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 +/// note | "技術詳細" + +実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + +また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + +`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + +`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 - また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 +/// - `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 +/// tip | "豆知識" - `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 +型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 -!!! tip "豆知識" - 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 +/// ## 追加情報の追加 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 2ba10c583..c051fde24 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -12,8 +12,11 @@ {!../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "備考" - この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 +/// note | "備考" + +この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +/// ## 複数のボディパラメータ @@ -53,8 +56,11 @@ } ``` -!!! note "備考" - 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 +/// note | "備考" + +以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +/// **FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 @@ -112,9 +118,11 @@ q: str = None {!../../../docs_src/body_multiple_params/tutorial004.py!} ``` -!!! info "情報" - `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// info | "情報" + +`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// ## 単一のボディパラメータの埋め込み diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 092e25798..59ee67295 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -162,8 +162,11 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する } ``` -!!! info "情報" - `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 +/// info | "情報" + +`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +/// ## 深くネストされたモデル @@ -173,8 +176,11 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "情報" - `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 +/// info | "情報" + +`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +/// ## 純粋なリストのボディ @@ -222,14 +228,17 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "豆知識" - JSONはキーとして`str`しかサポートしていないことに注意してください。 +/// tip | "豆知識" + +JSONはキーとして`str`しかサポートしていないことに注意してください。 + +しかしPydanticには自動データ変換機能があります。 - しかしPydanticには自動データ変換機能があります。 +これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 - これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 +そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 - そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 95d328ec5..672a03a64 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -34,14 +34,17 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -!!! note "備考" - `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 +/// note | "備考" - また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 +`PATCH`は`PUT`よりもあまり使われておらず、知られていません。 - **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 +また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 - しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 +**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 + +しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 + +/// ### Pydanticの`exclude_unset`パラメータの使用 @@ -86,14 +89,20 @@ {!../../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "豆知識" - 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 +/// tip | "豆知識" + +実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 + +しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 + +/// + +/// note | "備考" - しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 +入力モデルがまだ検証されていることに注目してください。 -!!! note "備考" - 入力モデルがまだ検証されていることに注目してください。 +そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 - そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 +**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 - **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 +/// diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index ccce9484d..017ff8986 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -8,12 +8,15 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 -!!! info "情報" - データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 +/// info | "情報" - GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 +データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 - 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 +GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 + +非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 + +/// ## Pydanticの `BaseModel` をインポート @@ -110,16 +113,19 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ -!!! tip "豆知識" - PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 +/// tip | "豆知識" + +PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 - 以下のエディターサポートが強化されます: +以下のエディターサポートが強化されます: - * 自動補完 - * 型チェック - * リファクタリング - * 検索 - * インスペクション +* 自動補完 +* 型チェック +* リファクタリング +* 検索 +* インスペクション + +/// ## モデルの使用 @@ -155,10 +161,13 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 +/// note | "備考" + +FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 + +`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 +/// ## Pydanticを使わない方法 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 193be305f..212885209 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/cookie_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | "技術詳細" - しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | "情報" + +クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## まとめ diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9d6ce8cdc..738240342 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -78,7 +78,10 @@ CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。 -!!! note "技術詳細" - `from starlette.middleware.cors import CORSMiddleware` も使用できます。 +/// note | "技術詳細" - **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 +`from starlette.middleware.cors import CORSMiddleware` も使用できます。 + +**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 + +/// diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 35e1ca7ad..06b8ad277 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app は実行されません。 -!!! info "情報" - より詳しい情報は、公式Pythonドキュメントを参照してください。 +/// info | "情報" + +より詳しい情報は、公式Pythonドキュメントを参照してください。 + +/// ## デバッガーでコードを実行 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 5c150d00c..69b67d042 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -185,7 +185,10 @@ commons: CommonQueryParams = Depends() ...そして **FastAPI** は何をすべきか知っています。 -!!! tip "豆知識" - 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 +/// tip | "豆知識" - それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 +役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + +それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 + +/// diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 1684d9ca1..c6472cab5 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,12 +20,15 @@ これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 -!!! tip "豆知識" - エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 +/// tip | "豆知識" - `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 +エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 - また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 +`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 + +また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 + +/// ## 依存関係のエラーと戻り値 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index c0642efd4..3f22a7a7b 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,27 +4,36 @@ FastAPIは、いくつかの以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`ことでコンテキストマネージャを作成することができます。 @@ -210,16 +237,19 @@ Pythonでは、`@contextlib.contextmanager` または +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` または - * `@contextlib.asynccontextmanager` +これらを使って、関数を単一の`yield`でデコレートすることができます。 - これらを使って、関数を単一の`yield`でデコレートすることができます。 +これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 - これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 +しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 - しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 +FastAPIが内部的にやってくれます。 - FastAPIが内部的にやってくれます。 +/// diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md index ec563a16d..000148d1c 100644 --- a/docs/ja/docs/tutorial/dependencies/index.md +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -75,8 +75,11 @@ そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 -!!! tip "豆知識" - 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 +/// tip | "豆知識" + +次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +/// 新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: @@ -97,10 +100,13 @@ common_parameters --> read_users この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 -!!! check "確認" - 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 +/// check | "確認" + +特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 - `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 +`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +/// ## `async`にするかどうか @@ -112,8 +118,11 @@ common_parameters --> read_users それは重要ではありません。**FastAPI** は何をすべきかを知っています。 -!!! note "備考" - わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 +/// note | "備考" + +わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +/// ## OpenAPIとの統合 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md index 8848ac79e..e183f28ba 100644 --- a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -41,10 +41,13 @@ {!../../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "情報" - *path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 +/// info | "情報" - しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 +*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 + +しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 + +/// ```mermaid graph TB @@ -78,9 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。 -!!! tip "豆知識" - これらの単純な例では、全てが役に立つとは言えないかもしれません。 +/// tip | "豆知識" + +これらの単純な例では、全てが役に立つとは言えないかもしれません。 + +しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 - しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 +そして、あなたを救うコードの量もみることになるでしょう。 - そして、あなたを救うコードの量もみることになるでしょう。 +/// diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md index 305867ab7..086e1fc63 100644 --- a/docs/ja/docs/tutorial/encoder.md +++ b/docs/ja/docs/tutorial/encoder.md @@ -30,5 +30,8 @@ Pydanticモデルのようなオブジェクトを受け取り、JSON互換版 これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。 -!!! note "備考" - `jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 +/// note | "備考" + +`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 + +/// diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md index aa2e5ffdc..90a22d3fa 100644 --- a/docs/ja/docs/tutorial/extra-models.md +++ b/docs/ja/docs/tutorial/extra-models.md @@ -8,10 +8,13 @@ * **出力モデル**はパスワードをもつべきではありません。 * **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 -!!! danger "危険" - ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 +/// danger | "危険" - 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 +ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + +知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +/// ## 複数のモデル @@ -131,8 +134,11 @@ UserInDB( ) ``` -!!! warning "注意" - サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 +/// warning | "注意" + +サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +/// ## 重複の削減 diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index f79ed94a4..dbe8e4518 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "備考" - `uvicorn main:app`は以下を示します: +/// note | "備考" - * `main`: `main.py`ファイル (Python "module")。 - * `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 - * `--reload`: コードの変更時にサーバーを再起動させる。開発用。 +`uvicorn main:app`は以下を示します: + +* `main`: `main.py`ファイル (Python "module")。 +* `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 +* `--reload`: コードの変更時にサーバーを再起動させる。開発用。 + +/// 出力には次のような行があります: @@ -136,10 +139,13 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 -!!! note "技術詳細" - `FastAPI`は`Starlette`を直接継承するクラスです。 +/// note | "技術詳細" + +`FastAPI`は`Starlette`を直接継承するクラスです。 - `FastAPI`でもStarletteのすべての機能を利用可能です。 +`FastAPI`でもStarletteのすべての機能を利用可能です。 + +/// ### Step 2: `FastAPI`の「インスタンス」を生成 @@ -198,8 +204,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "情報" - 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 +/// info | "情報" + +「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 + +/// APIを構築する際、「パス」は「関心事」と「リソース」を分離するための主要な方法です。 @@ -248,16 +257,19 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * パス `/` * get オペレーション -!!! info "`@decorator` について" - Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 +/// info | "`@decorator` について" - 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 +Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 - 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 +「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 - 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 +「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 - これが「*パスオペレーションデコレータ*」です。 +私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 + +これが「*パスオペレーションデコレータ*」です。 + +/// 他のオペレーションも使用できます: @@ -272,14 +284,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * `@app.patch()` * `@app.trace()` -!!! tip "豆知識" - 各オペレーション (HTTPメソッド)は自由に使用できます。 +/// tip | "豆知識" + +各オペレーション (HTTPメソッド)は自由に使用できます。 - **FastAPI**は特定の意味づけを強制しません。 +**FastAPI**は特定の意味づけを強制しません。 - ここでの情報は、要件ではなくガイドラインとして提示されます。 +ここでの情報は、要件ではなくガイドラインとして提示されます。 - 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 +例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 + +/// ### Step 4: **パスオペレーション**を定義 @@ -307,8 +322,11 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "備考" - 違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 +/// note | "備考" + +違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 + +/// ### Step 5: コンテンツの返信 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 0b95cae0f..8be054858 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ Pythonの例外なので、`return`ではなく、`raise`です。 } ``` -!!! tip "豆知識" - `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 +/// tip | "豆知識" - `dist`や`list`などを渡すことができます。 +`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 - これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 +`dist`や`list`などを渡すことができます。 + +これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +/// ## カスタムヘッダーの追加 @@ -106,10 +109,13 @@ Pythonの例外なので、`return`ではなく、`raise`です。 {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "技術詳細" - また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 +/// ## デフォルトの例外ハンドラのオーバーライド @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError`と`ValidationError` -!!! warning "注意" - これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 +/// warning | "注意" + +これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +/// `RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import PlainTextResponse`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `RequestValidationError`のボディの使用 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 1bf8440bb..4fab3d423 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/header_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | "技術詳細" - しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | "情報" + +ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## 自動変換 @@ -48,9 +54,11 @@ {!../../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "注意" - `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// warning | "注意" + +`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// ## ヘッダーの重複 diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 856cde44b..c5fe27259 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! note "備考" - パーツ毎にインストールすることも可能です。 +/// note | "備考" - 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: +パーツ毎にインストールすることも可能です。 - ``` - pip install fastapi - ``` +以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: - また、サーバーとして動作するように`uvicorn` をインストールします: +``` +pip install fastapi +``` + +また、サーバーとして動作するように`uvicorn` をインストールします: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +そして、使用したい依存関係をそれぞれ同様にインストールします。 - そして、使用したい依存関係をそれぞれ同様にインストールします。 +/// ## 高度なユーザーガイド diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 73d7f02b2..eb85dc389 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -47,8 +47,11 @@ 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 -!!! tip "豆知識" - 使用するすべてのタグにメタデータを追加する必要はありません。 +/// tip | "豆知識" + +使用するすべてのタグにメタデータを追加する必要はありません。 + +/// ### 自作タグの使用 @@ -58,8 +61,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info "情報" - タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 +/// info | "情報" + +タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 + +/// ### ドキュメントの確認 diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 973eb2b1a..05e1b7a8c 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。 * そして、**レスポンス**を返します。 -!!! note "技術詳細" - `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 +/// note | "技術詳細" - バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 +`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 + +バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 + +/// ## ミドルウェアの作成 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "豆知識" - 'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 +/// tip | "豆知識" + +'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 + +ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) + +/// + +/// note | "技術詳細" - ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) +`from starlette.requests import Request` を使用することもできます。 -!!! note "技術詳細" - `from starlette.requests import Request` を使用することもできます。 +**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 - **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 +/// ### `response` の前後 diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 486c4b204..def12bd08 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ *path operationデコレータ*を設定するためのパラメータがいくつかあります。 -!!! warning "注意" - これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 +/// warning | "注意" + +これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 + +/// ## レスポンスステータスコード @@ -19,10 +22,13 @@ そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 -!!! note "技術詳細" - また、`from starlette import status`を使用することもできます。 +/// note | "技術詳細" + +また、`from starlette import status`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 +/// ## タグ @@ -66,13 +72,19 @@ docstringに diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 551aeabb3..9f0b72585 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -20,12 +20,15 @@ {!../../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "備考" - パスの一部でなければならないので、パスパラメータは常に必須です。 +/// note | "備考" - そのため、`...`を使用して必須と示す必要があります。 +パスの一部でなければならないので、パスパラメータは常に必須です。 - それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 +そのため、`...`を使用して必須と示す必要があります。 + +それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +/// ## 必要に応じてパラメータを並び替える @@ -105,18 +108,24 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `lt`: より小さい(`l`ess `t`han) * `le`: 以下(`l`ess than or `e`qual) -!!! info "情報" - `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) +/// info | "情報" + +`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + +そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +/// + +/// note | "技術詳細" - そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 +`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 -!!! note "技術詳細" - `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 +呼び出されると、同じ名前のクラスのインスタンスを返します。 - 呼び出されると、同じ名前のクラスのインスタンスを返します。 +そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 - そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 +これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 - これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 +この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 - この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 +/// diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index b395dc41d..0a7916012 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ここでは、 `item_id` は `int` として宣言されています。 -!!! check "確認" - これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 +/// check | "確認" + +これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 + +/// ## データ変換 @@ -35,10 +38,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -!!! check "確認" - 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 +/// check | "確認" + +関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 + +したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 - したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 +/// ## データバリデーション @@ -63,12 +69,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -!!! check "確認" - したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 +/// check | "確認" - 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 +したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 - これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 +表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 + +これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 + +/// ## ドキュメント @@ -76,10 +85,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -!!! check "確認" - 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 +/// check | "確認" + +繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 + +パスパラメータが整数として宣言されていることに注意してください。 - パスパラメータが整数として宣言されていることに注意してください。 +/// ## 標準であることのメリット、ドキュメンテーションの代替物 @@ -131,11 +143,17 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "情報" - Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 +/// info | "情報" -!!! tip "豆知識" - "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 +Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 + +/// + +/// tip | "豆知識" + +"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 + +/// ### *パスパラメータ*の宣言 @@ -171,8 +189,11 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "豆知識" - `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 +/// tip | "豆知識" + +`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 + +/// #### *列挙型メンバ*の返却 @@ -225,10 +246,13 @@ Starletteのオプションを直接使用することで、以下のURLの様 {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "豆知識" - 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 +/// tip | "豆知識" + +最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 + +この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 - この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 8d375d7ce..ada048844 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,14 @@ クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -!!! note "備考" - FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 +/// note | "備考" + +FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 + +`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 + +/// - `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 ## バリデーションの追加 `q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。 @@ -50,22 +54,25 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -!!! info "情報" - FastAPIは以下の部分を気にすることを覚えておいてください: +/// info | "情報" + +FastAPIは以下の部分を気にすることを覚えておいてください: + +```Python += None +``` - ```Python - = None - ``` +もしくは: - もしくは: +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 - そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 +`Optional` の部分は、エディターによるより良いサポートを可能にします。 - `Optional` の部分は、エディターによるより良いサポートを可能にします。 +/// そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。 @@ -111,8 +118,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "備考" - デフォルト値を指定すると、パラメータは任意になります。 +/// note | "備考" + +デフォルト値を指定すると、パラメータは任意になります。 + +/// ## 必須にする @@ -140,8 +150,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "情報" - これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 +/// info | "情報" + +これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 + +/// これは **FastAPI** にこのパラメータが必須であることを知らせます。 @@ -174,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "豆知識" - 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 +/// tip | "豆知識" + +上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 + +/// 対話的APIドキュメントは複数の値を許可するために自動的に更新されます。 @@ -214,10 +230,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "備考" - この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 +/// note | "備考" - 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 +この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 + +例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 + +/// ## より多くのメタデータを宣言する @@ -225,10 +244,13 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -!!! note "備考" - ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 +/// note | "備考" + +ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 + +その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 - その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 +/// `title`を追加できます: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 5c4cfc5fc..c0eb2d096 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -1,4 +1,3 @@ - # クエリパラメータ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 @@ -70,8 +69,11 @@ http://127.0.0.1:8000/items/?skip=20 この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -!!! check "確認" - パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 +/// check | "確認" + +パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 + +/// ## クエリパラメータの型変換 @@ -189,6 +191,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -!!! tip "豆知識" +/// tip | "豆知識" + +[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 - [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 +/// diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index 86913ccac..d8effc219 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ `File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 -!!! info "情報" - アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 +/// info | "情報" - 例えば、`pip install python-multipart`のように。 +アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 + +例えば、`pip install python-multipart`のように。 + +/// ## `File`と`Form`のインポート @@ -25,10 +28,13 @@ また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 -!!! warning "注意" - *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 +/// warning | "注意" + +*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 + +これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index f90c49746..d04dc810b 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -!!! info "情報" - フォームを使うためには、まず`python-multipart`をインストールします。 +/// info | "情報" - たとえば、`pip install python-multipart`のように。 +フォームを使うためには、まず`python-multipart`をインストールします。 + +たとえば、`pip install python-multipart`のように。 + +/// ## `Form`のインポート @@ -29,11 +32,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -!!! info "情報" - `Form`は`Body`を直接継承するクラスです。 +/// info | "情報" + +`Form`は`Body`を直接継承するクラスです。 + +/// + +/// tip | "豆知識" -!!! tip "豆知識" - フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 +フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 + +/// ## 「フォームフィールド」について @@ -41,17 +50,23 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -!!! note "技術詳細" - フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 +/// note | "技術詳細" + +フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 + +しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 + +これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 + +/// - しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 +/// warning | "注意" - これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 +*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 -!!! warning "注意" - *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 +これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index b8b6978d4..7bb5e2825 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -12,8 +12,11 @@ {!../../../docs_src/response_model/tutorial001.py!} ``` -!!! note "備考" - `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 +/// note | "備考" + +`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +/// Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 @@ -28,8 +31,11 @@ FastAPIは`response_model`を使って以下のことをします: * 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 -!!! note "技術詳細" - レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 +/// note | "技術詳細" + +レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +/// ## 同じ入力データの返却 @@ -51,8 +57,11 @@ FastAPIは`response_model`を使って以下のことをします: しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 -!!! danger "危険" - ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 +/// danger | "危険" + +ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +/// ## 出力モデルの追加 @@ -121,16 +130,22 @@ FastAPIは`response_model`を使って以下のことをします: } ``` -!!! info "情報" - FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 +/// info | "情報" + +FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 + +/// -!!! info "情報" - 以下も使用することができます: +/// info | "情報" - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +以下も使用することができます: - `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 + +/// #### デフォルト値を持つフィールドの値を持つデータ @@ -165,9 +180,12 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d そのため、それらはJSONレスポンスに含まれることになります。 -!!! tip "豆知識" - デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 - 例えば、リスト(`[]`)や`10.5`の`float`などです。 +/// tip | "豆知識" + +デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 +例えば、リスト(`[]`)や`10.5`の`float`などです。 + +/// ### `response_model_include`と`response_model_exclude` @@ -177,21 +195,27 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 -!!! tip "豆知識" - それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 +/// tip | "豆知識" - これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 +それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 - 同様に動作する`response_model_by_alias`にも当てはまります。 +これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + +同様に動作する`response_model_by_alias`にも当てはまります。 + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "豆知識" - `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 +/// tip | "豆知識" + +`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + +これは`set(["name", "description"])`と同等です。 - これは`set(["name", "description"])`と同等です。 +/// #### `set`の代わりに`list`を使用する diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index ead2addda..945767894 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "備考" - `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 +/// note | "備考" + +`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +/// `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -!!! info "情報" - `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 +/// info | "情報" + +`status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 + +/// これは: @@ -27,15 +33,21 @@ -!!! note "備考" - いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 +/// note | "備考" + +いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + +FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 - FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 +/// ## HTTPステータスコードについて -!!! note "備考" - すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 +/// note | "備考" + +すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +/// HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 @@ -54,8 +66,11 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス * クライアントからの一般的なエラーについては、`400`を使用することができます。 * `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 -!!! tip "豆知識" - それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 +/// tip | "豆知識" + +それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 + +/// ## 名前を覚えるための近道 @@ -79,10 +94,13 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス -!!! note "技術詳細" - また、`from starlette import status`を使うこともできます。 +/// note | "技術詳細" + +また、`from starlette import status`を使うこともできます。 + +**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 - **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 +/// ## デフォルトの変更 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index d96163b82..a3cd5eb54 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -24,8 +24,11 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 {!../../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "注意" - これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 +/// warning | "注意" + +これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +/// ## `Body`の追加引数 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index dc3267e62..c78a3755e 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -26,12 +26,15 @@ ## 実行 -!!! info "情報" - まず`python-multipart`をインストールします。 +/// info | "情報" - 例えば、`pip install python-multipart`。 +まず`python-multipart`をインストールします。 - これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 +例えば、`pip install python-multipart`。 + +これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 + +/// 例を実行します: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload -!!! check "Authorizeボタン!" - すでにピカピカの新しい「Authorize」ボタンがあります。 +/// check | "Authorizeボタン!" + +すでにピカピカの新しい「Authorize」ボタンがあります。 + +そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 - そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 +/// それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます: -!!! note "備考" - フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 +/// note | "備考" + +フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 + +/// もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。 @@ -105,14 +114,17 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -!!! info "情報" - 「bearer」トークンが、唯一の選択肢ではありません。 +/// info | "情報" + +「bearer」トークンが、唯一の選択肢ではありません。 - しかし、私たちのユースケースには最適です。 +しかし、私たちのユースケースには最適です。 - あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 +あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 - その場合、**FastAPI**はそれを構築するためのツールも提供します。 +その場合、**FastAPI**はそれを構築するためのツールも提供します。 + +/// `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 @@ -120,21 +132,27 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "豆知識" - ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 +/// tip | "豆知識" + +ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 - 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 +相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 - 相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 +相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 + +/// このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。 実際のpath operationもすぐに作ります。 -!!! info "情報" - 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 +/// info | "情報" + +非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 - それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 +それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 + +/// 変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。 @@ -158,10 +176,13 @@ oauth2_scheme(some, parameters) **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -!!! info "技術詳細" - **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 +/// info | "技術詳細" + +**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 + +OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 - OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 +/// ## どのように動作するか diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 7f8dcaad2..250f66b81 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -54,17 +54,21 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 -!!! tip "豆知識" - リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +/// tip | "豆知識" - ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 +リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 -!!! check "確認" - 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 +/// - 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 +/// check | "確認" +依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 + +同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 + +/// ## 別のモデル diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md index 390f21047..c68e7e7f2 100644 --- a/docs/ja/docs/tutorial/security/index.md +++ b/docs/ja/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 -!!! tip "豆知識" - **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 +/// tip | "豆知識" +**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPIでは、以下のセキュリティスキームを定義しています: * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 -!!! tip "豆知識" - Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 +/// tip | "豆知識" + +Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 + +最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 - 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 +/// ## **FastAPI** ユーティリティ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index d5b179aa0..4f6aebd4c 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:pyca/cryptography。 -!!! tip "豆知識" - このチュートリアルでは以前、PyJWTを使用していました。 +/// tip | "豆知識" - しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 +このチュートリアルでは以前、PyJWTを使用していました。 + +しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 + +/// ## パスワードのハッシュ化 @@ -83,13 +86,15 @@ $ pip install passlib[bcrypt] -!!! tip "豆知識" - `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 +/// tip | "豆知識" + +`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 - 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 +例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 - また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +/// ## パスワードのハッシュ化と検証 @@ -97,12 +102,15 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -!!! tip "豆知識" - PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 +/// tip | "豆知識" - 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 +PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 - そして、同時にそれらはすべてに互換性があります。 +例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 + +そして、同時にそれらはすべてに互換性があります。 + +/// ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。 @@ -114,8 +122,11 @@ PassLib の「context」を作成します。これは、パスワードのハ {!../../../docs_src/security/tutorial004.py!} ``` -!!! note "備考" - 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` +/// note | "備考" + +新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` + +/// ## JWTトークンの取り扱い @@ -208,8 +219,11 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -!!! check "確認" - コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 +/// check | "確認" + +コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 + +/// @@ -230,8 +244,11 @@ Password: `secret` -!!! note "備考" - ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 +/// note | "備考" + +ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 + +/// ## `scopes` を使った高度なユースケース diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 1d9c434c3..c9d95bc34 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.staticfiles import StaticFiles` も使用できます。 +/// note | "技術詳細" - **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 +`from starlette.staticfiles import StaticFiles` も使用できます。 + +**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// ### 「マウント」とは diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 037e9628f..3ed03ebea 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -22,20 +22,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "豆知識" - テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 +/// tip | "豆知識" - また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 +テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 - これにより、煩雑にならずに、`pytest` を直接使用できます。 +また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 -!!! note "技術詳細" - `from starlette.testclient import TestClient` も使用できます。 +これにより、煩雑にならずに、`pytest` を直接使用できます。 - **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 +/// -!!! tip "豆知識" - FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 +/// note | "技術詳細" + +`from starlette.testclient import TestClient` も使用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// + +/// tip | "豆知識" + +FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 + +/// ## テストの分離 @@ -74,17 +83,21 @@ これらの *path operation* には `X-Token` ヘッダーが必要です。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 拡張版テストファイル @@ -108,10 +121,13 @@ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。 -!!! info "情報" - `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 +/// info | "情報" + +`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 + +テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 - テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 +/// ## 実行 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index d3227497b..e155f41f1 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -4,8 +4,11 @@ 이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. -!!! warning "경고" - 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. +/// warning | "경고" + +이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. + +/// ## `startup` 이벤트 @@ -31,15 +34,24 @@ 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. -!!! info "정보" - `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. +/// info | "정보" + +`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. + +/// + +/// tip | "팁" + +이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. + +따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. + +그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. -!!! tip "팁" - 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. +/// - 따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. +/// info | "정보" - 그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. +이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. -!!! info "정보" - 이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. +/// diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index 5fd1711a1..cb628fa10 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -6,10 +6,13 @@ 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. -!!! tip "팁" - 다음 장들이 **반드시 "심화"**인 것은 아닙니다. +/// tip | "팁" - 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. +다음 장들이 **반드시 "심화"**인 것은 아닙니다. + +그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +/// ## 자습서를 먼저 읽으십시오 diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 65ee124ec..dfc2caa78 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "참고" - `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. +/// note | "참고" + +`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. + +/// --- @@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 도커파일 미리보기 👀 @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info "정보" - 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. +/// info | "정보" + +패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. - 나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 +나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 + +/// ### **FastAPI** 코드 생성하기 @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. -!!! tip "팁" - 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 +/// tip | "팁" + +각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 + +/// 이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다: @@ -293,10 +302,13 @@ $ docker build -t myimage . -!!! tip "팁" - 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. +/// tip | "팁" + +맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. + +이 경우에는 현재 디렉터리(`.`)와 같습니다. - 이 경우에는 현재 디렉터리(`.`)와 같습니다. +/// ### 도커 컨테이너 시작하기 @@ -394,8 +406,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] **HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. -!!! tip "팁" - Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. +/// tip | "팁" + +Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. + +/// 대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다). @@ -423,8 +438,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. -!!! tip "팁" - HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. +/// tip | "팁" + +HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. + +/// 또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다). @@ -503,8 +521,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. -!!! info "정보" - 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. +/// info | "정보" + +만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. + +/// 만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다. @@ -520,8 +541,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "경고" - 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. +/// warning | "경고" + +여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. + +/// 이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다. @@ -529,8 +553,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. -!!! tip "팁" - 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | "팁" + +모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### 공식 도커 이미지에 있는 프로세스 개수 @@ -657,8 +684,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. -!!! tip "팁" - 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. +/// tip | "팁" + +버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. + +/// **도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다. diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index f7ef96094..39976faf5 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ 지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -!!! info "정보" - 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. +/// info | "정보" - 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. +만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. + +특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. + +/// ## 구니콘과 유비콘 워커 diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index 074c15158..f3b3c2d7b 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,8 +43,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -!!! tip "팁" - 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. +/// tip | "팁" + +여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. + +/// 따라서 다음과 같이 버전을 표시할 수 있습니다: @@ -54,8 +57,11 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -!!! tip "팁" - "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. +/// tip | "팁" + +"마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. + +/// ## FastAPI 버전의 업그레이드 diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index ca1940a21..b6f6f7af2 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "정보" - `**second_user_data`가 뜻하는 것: +/// info | "정보" - `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data`가 뜻하는 것: + +`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 편집기 지원 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 267ce6c7e..5c458e48d 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -12,8 +12,11 @@ 비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. -!!! note "참고" - 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. +/// note | "참고" + +파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. + +/// ## 동기 부여 @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "팁" - 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. +/// tip | "팁" + +대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. + +이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. - 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. +/// 이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다. @@ -281,9 +287,11 @@ Pydantic 공식 문서 예시: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "정보" - Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. +/// info | "정보" +Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. + +/// **FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. @@ -311,5 +319,8 @@ Pydantic 공식 문서 예시: 가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠. -!!! info "정보" - 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. +/// info | "정보" + +만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. + +/// diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index ee83d6570..880a1c198 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -=== "Python 3.6 and above" +//// tab | Python 3.6 and above - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index c91d6130b..b74722e26 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ 먼저 이를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -!!! warning "경고" - `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "경고" + +`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. + +/// ## 모델 어트리뷰트 선언 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ Annotated가 없는 경우" +//// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip | "팁" -=== "Python 3.8+ Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. -!!! note "기술적 세부사항" - 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. +/// note | "기술적 세부사항" - 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. +실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. - `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. +그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. - `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. +`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. -!!! tip "팁" - 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. + +/// + +/// tip | "팁" + +주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + +/// ## 별도 정보 추가 @@ -105,9 +146,12 @@ 여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. -!!! warning "경고" - 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. - 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. +/// warning | "경고" + +별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. +이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. + +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 2cf5df7f3..023575e1b 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -14,8 +14,11 @@ {!../../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "참고" - 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. +/// note | "참고" + +이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. + +/// ## 다중 본문 매개변수 @@ -55,8 +58,11 @@ } ``` -!!! note "참고" - 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. +/// note | "참고" + +이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. + +/// FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다. @@ -114,8 +120,11 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 q: Optional[str] = None ``` -!!! info "정보" - `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. +/// info | "정보" + +`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. + +/// ## 단일 본문 매개변수 삽입하기 diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 10af0a062..4d785f64b 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -161,8 +161,11 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. } ``` -!!! info "정보" - `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. +/// info | "정보" + +`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. + +/// ## 깊게 중첩된 모델 @@ -172,8 +175,11 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "정보" - `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 +/// info | "정보" + +`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 + +/// ## 순수 리스트의 본문 @@ -221,14 +227,17 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "팁" - JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. +/// tip | "팁" + +JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. + +하지만 Pydantic은 자동 데이터 변환이 있습니다. - 하지만 Pydantic은 자동 데이터 변환이 있습니다. +즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. - 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. +그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. - 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 0ab8b7162..337218eb4 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,28 +8,35 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. -!!! info "정보" - 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. +/// info | "정보" - `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. +데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. - `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. +`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. + +`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. + +/// ## Pydantic의 `BaseModel` 임포트 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## 여러분의 데이터 모델 만들기 @@ -37,17 +44,21 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -75,17 +86,21 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -134,32 +149,39 @@ -!!! tip "팁" - 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. +/// tip | "팁" + +만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. - 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: +다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: - * 자동 완성 - * 타입 확인 - * 리팩토링 - * 검색 - * 점검 +* 자동 완성 +* 타입 확인 +* 리팩토링 +* 검색 +* 점검 + +/// ## 모델 사용하기 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## 요청 본문 + 경로 매개변수 @@ -167,17 +189,21 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -185,17 +211,21 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` + +//// 함수 매개변수는 다음을 따라서 인지하게 됩니다: @@ -203,10 +233,13 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -!!! note "참고" - FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. +/// note | "참고" + +FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. - `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. +/// ## Pydantic없이 diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index d4f3d57a3..5f129b63f 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 먼저 `Cookie`를 임포트합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie` 매개변수 선언 @@ -48,49 +64,71 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ Annotated가 없는 경우 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | "팁" -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ Annotated가 없는 경우" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "기술 세부사항" -=== "Python 3.8+ Annotated가 없는 경우" +`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "기술 세부사항" - `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// info | "정보" - `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. +쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. -!!! info "정보" - 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 39e9ea83f..312fdee1b 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -78,7 +78,10 @@ CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다. -!!! note "기술적 세부 사항" - `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. +/// note | "기술적 세부 사항" - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. +`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. + +/// diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index c3e588537..cb45e5169 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app 은 실행되지 않습니다. -!!! info "정보" - 자세한 내용은 공식 Python 문서를 확인하세요 +/// info | "정보" + +자세한 내용은 공식 Python 문서를 확인하세요 + +/// ## 디버거로 코드 실행 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 38cdc2e1a..259fe4b6d 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -77,45 +81,57 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -131,17 +147,21 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -180,17 +200,21 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -224,21 +248,28 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. -!!! tip "팁" - 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. +/// tip | "팁" + +만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. + +이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. - 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. +/// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 92b2c7d1c..bc8af488d 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ `Depends()`로 된 `list`이어야합니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. -!!! tip "팁" - 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. +/// tip | "팁" + +일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. - *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. +*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. - 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. +또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. -!!! info "정보" - 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. +/// - 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. +/// info | "정보" + +이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. + +그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. + +/// ## 의존성 오류와 값 반환하기 @@ -57,51 +72,69 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8 Annotated가 없는 경우" +/// tip | "팁" - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 Annotated가 없는 경우 - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | "팁" -=== "Python 3.8 Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 값 반환하기 @@ -109,26 +142,35 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8+" +/// tip | "팁" - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8 Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 930f6e678..2ce2cf4f2 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index d06864ab8..361989e2b 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ Annotated가 없는 경우 -=== "Python 3.10+ Annotated가 없는 경우" +/// tip | "팁" - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ Annotated가 없는 경우" +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// 이게 다입니다. @@ -85,90 +101,125 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -!!! info "정보" - FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. +/// info | "정보" + +FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. - 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. +옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. - `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. +`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. + +/// ### `Depends` 불러오기 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | "팁" -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -180,8 +231,11 @@ 그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. -!!! tip "팁" - 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. +/// tip | "팁" + +여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. + +/// 새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다: @@ -202,10 +256,13 @@ common_parameters --> read_users 이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. -!!! check "확인" - 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. +/// check | "확인" + +특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. + +단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. - 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. +/// ## `Annotated`인 의존성 공유하기 @@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | "팁" -!!! tip "팁" - 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. +이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. - 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 +하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 + +/// 이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다. @@ -256,8 +322,11 @@ commons: Annotated[dict, Depends(common_parameters)] 아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. -!!! note "참고" - 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. +/// note | "참고" + +잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. + +/// ## OpenAPI와 통합 diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 8b5fdb8b7..b8e87449c 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -30,5 +30,8 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -!!! note "참고" - 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. +/// note | "참고" + +실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. + +/// diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index 673cf5b73..df3c7a06e 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// 함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index bdec3a377..52e53fd89 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "참고" - `uvicorn main:app` 명령은 다음을 의미합니다: +/// note | "참고" - * `main`: 파일 `main.py` (파이썬 "모듈"). - * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. - * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. +`uvicorn main:app` 명령은 다음을 의미합니다: + +* `main`: 파일 `main.py` (파이썬 "모듈"). +* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. +* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. + +/// 출력되는 줄들 중에는 아래와 같은 내용이 있습니다: @@ -136,10 +139,13 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -!!! note "기술 세부사항" - `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. +/// note | "기술 세부사항" + +`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. - `FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. +`FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. + +/// ### 2 단계: `FastAPI` "인스턴스" 생성 @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "정보" - "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. +/// info | "정보" + +"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. + +/// API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다. @@ -250,16 +259,19 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * 경로 `/` * get 작동 사용 -!!! info "`@decorator` 정보" - 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. +/// info | "`@decorator` 정보" - 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. +이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. - "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. +마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. - 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. +"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. - 이것이 "**경로 작동 데코레이터**"입니다. +우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. + +이것이 "**경로 작동 데코레이터**"입니다. + +/// 다른 작동도 사용할 수 있습니다: @@ -274,14 +286,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * `@app.patch()` * `@app.trace()` -!!! tip "팁" - 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. +/// tip | "팁" + +각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. - **FastAPI**는 특정 의미를 강제하지 않습니다. +**FastAPI**는 특정 의미를 강제하지 않습니다. - 여기서 정보는 지침서일뿐 강제사항이 아닙니다. +여기서 정보는 지침서일뿐 강제사항이 아닙니다. - 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. +예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. + +/// ### 4 단계: **경로 작동 함수** 정의 @@ -309,8 +324,11 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "참고" - 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. +/// note | "참고" + +차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. + +/// ### 5 단계: 콘텐츠 반환 diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 484554e97..d403b9175 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -20,13 +20,19 @@ {!../../../docs_src/header_params/tutorial001.py!} ``` -!!! note "기술 세부사항" - `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// note | "기술 세부사항" - `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. +`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. -!!! info "정보" - 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. + +/// + +/// info | "정보" + +헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +/// ## 자동 변환 @@ -48,8 +54,11 @@ {!../../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "경고" - `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. +/// warning | "경고" + +`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. + +/// ## 중복 헤더 diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index 94d6dfb92..d00a942f0 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -53,22 +53,25 @@ $ pip install "fastapi[all]" ...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. -!!! note "참고" - 부분적으로 설치할 수도 있습니다. +/// note | "참고" - 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: +부분적으로 설치할 수도 있습니다. - ``` - pip install fastapi - ``` +애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: - 추가로 서버 역할을 하는 `uvicorn`을 설치합니다: +``` +pip install fastapi +``` + +추가로 서버 역할을 하는 `uvicorn`을 설치합니다: + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +사용하려는 각 선택적인 의존성에 대해서도 동일합니다. - 사용하려는 각 선택적인 의존성에 대해서도 동일합니다. +/// ## 고급 사용자 안내서 diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index f35b446a6..84f67bd26 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. * **응답**를 반환합니다. -!!! note "기술 세부사항" - 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. +/// note | "기술 세부사항" - 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. +만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. + +만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. + +/// ## 미들웨어 만들기 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "팁" - 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. +/// tip | "팁" + +사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. + +그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. + +/// + +/// note | "기술적 세부사항" - 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. +`from starlette.requests import request`를 사용할 수도 있습니다. -!!! note "기술적 세부사항" - `from starlette.requests import request`를 사용할 수도 있습니다. +**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. - **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. +/// ### `response`의 전과 후 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 411c43493..b6608a14d 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ *경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. -!!! warning "경고" - 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. +/// warning | "경고" + +아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. + +/// ## 응답 상태 코드 @@ -19,10 +22,13 @@ 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. -!!! note "기술적 세부사항" - 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. +/// note | "기술적 세부사항" + +다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. + +**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. - **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. +/// ## 태그 @@ -66,13 +72,19 @@ {!../../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "정보" - `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. +/// info | "정보" + +`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. + +/// + +/// check | "확인" + +OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. -!!! check "확인" - OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. +따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. - 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. +/// diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index cadf543fc..6d3215c24 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -20,12 +20,15 @@ {!../../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "참고" - 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. +/// note | "참고" - 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. +경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. - 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. +즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. + +그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. + +/// ## 필요한 경우 매개변수 정렬하기 @@ -105,18 +108,24 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -!!! info "정보" - `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. +/// info | "정보" + +`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. + +그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. + +/// + +/// note | "기술 세부사항" - 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. +`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. -!!! note "기술 세부사항" - `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. +호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. - 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. +즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. - 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. +편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. - 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. +이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. - 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. +/// diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index a75c3cc8c..67a2d899d 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ 위의 예시에서, `item_id`는 `int`로 선언되었습니다. -!!! check "확인" - 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. +/// check | "확인" + +이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. + +/// ## 데이터 변환 @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "확인" - 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. +/// check | "확인" + +함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. + +즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. - 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. +/// ## 데이터 검증 @@ -63,12 +69,15 @@ `int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 -!!! check "확인" - 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. +/// check | "확인" - 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. +즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. - 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. +오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. + +이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. + +/// ## 문서화 @@ -76,10 +85,13 @@ -!!! check "확인" - 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. +/// check | "확인" + +그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. + +경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. - 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. +/// ## 표준 기반의 이점, 대체 문서 @@ -131,11 +143,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "정보" - 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. +/// info | "정보" -!!! tip "팁" - 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. +열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. + +/// + +/// tip | "팁" + +혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. + +/// ### *경로 매개변수* 선언 @@ -171,8 +189,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "팁" - `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. +/// tip | "팁" + +`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. + +/// #### *열거형 멤버* 반환 @@ -225,10 +246,13 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "팁" - 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. +/// tip | "팁" + +매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. + +이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. - 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 2e6396ccc..11193950b 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. -!!! note "참고" - FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. +/// note | "참고" - `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. +FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. + +`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. + +/// ## 추가 검증 @@ -51,22 +54,25 @@ q: Optional[str] = None 하지만 명시적으로 쿼리 매개변수를 선언합니다. -!!! info "정보" - FastAPI는 다음 부분에 관심이 있습니다: +/// info | "정보" - ```Python - = None - ``` +FastAPI는 다음 부분에 관심이 있습니다: - 또는: +```Python += None +``` - ```Python - = Query(None) - ``` +또는: - 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. +```Python += Query(None) +``` + +그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. - `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. +`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. + +/// 또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다: @@ -112,8 +118,11 @@ q: str = Query(None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "참고" - 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. +/// note | "참고" + +기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. + +/// ## 필수로 만들기 @@ -141,8 +150,11 @@ q: Optional[str] = Query(None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "정보" - 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. +/// info | "정보" + +이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. + +/// 이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다. @@ -175,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "팁" - 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. +/// tip | "팁" + +위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. + +/// 대화형 API 문서는 여러 값을 허용하도록 수정 됩니다: @@ -215,10 +230,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "참고" - 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. +/// note | "참고" - 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. +이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. + +예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. + +/// ## 더 많은 메타데이터 선언 @@ -226,10 +244,13 @@ http://localhost:8000/items/ 해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. -!!! note "참고" - 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. +/// note | "참고" + +도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. + +일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. - 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. +/// `title`을 추가할 수 있습니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 43a6c1a36..e71444c18 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -69,13 +69,19 @@ http://127.0.0.1:8000/items/?skip=20 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -!!! check "확인" - **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. +/// check | "확인" -!!! note "참고" - FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. +**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. - `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. +/// + +/// note | "참고" + +FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. + +/// ## 쿼리 매개변수 형변환 @@ -194,5 +200,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -!!! tip "팁" - [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. +/// tip | "팁" + +[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. + +/// diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 468c46283..b7781ef5e 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,12 +2,15 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -!!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | "정보" - 예시) `pip install python-multipart`. +업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. - 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. +예시) `pip install python-multipart`. + +업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. + +/// ## `File` 임포트 @@ -25,13 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info "정보" - `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. +/// info | "정보" + +`File` 은 `Form` 으로부터 직접 상속된 클래스입니다. + +하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. + +/// - 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. +/// tip | "팁" -!!! tip "팁" - File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. +File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. + +/// 파일들은 "폼 데이터"의 형태로 업로드 됩니다. @@ -89,11 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 기술적 세부사항" - `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. +/// note | "`async` 기술적 세부사항" + +`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. + +/// + +/// note | "Starlette 기술적 세부사항" -!!! note "Starlette 기술적 세부사항" - **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. +**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. + +/// ## "폼 데이터"란 @@ -101,17 +116,23 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -!!! note "기술적 세부사항" - 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. +/// note | "기술적 세부사항" + +폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. + +하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. + +인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. + +/// - 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. +/// warning | "경고" - 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. +다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. -!!! warning "경고" - 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 다중 파일 업로드 @@ -127,17 +148,23 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. -!!! note "참고" - 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. +/// note | "참고" + +2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. + +그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. + +따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. + +/// - 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. +/// note | "기술적 세부사항" - 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. +`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. -!!! note "기술적 세부사항" - `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index bd5f41918..0867414ea 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,10 +2,13 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -!!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | "정보" - 예 ) `pip install python-multipart`. +파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. + +예 ) `pip install python-multipart`. + +/// ## `File` 및 `Form` 업로드 @@ -25,10 +28,13 @@ 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -!!! warning "경고" - 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +/// warning | "경고" + +다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. + +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index feff88a42..fc74a60b3 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -12,8 +12,11 @@ {!../../../docs_src/response_model/tutorial001.py!} ``` -!!! note "참고" - `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. +/// note | "참고" + +`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. + +/// Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다. @@ -28,8 +31,11 @@ FastAPI는 이 `response_model`를 사용하여: * 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. -!!! note "기술 세부사항" - 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 +/// note | "기술 세부사항" + +응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 + +/// ## 동일한 입력 데이터 반환 @@ -51,8 +57,11 @@ FastAPI는 이 `response_model`를 사용하여: 그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. -!!! danger "위험" - 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. +/// danger | "위험" + +절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. + +/// ## 출력 모델 추가 @@ -121,16 +130,22 @@ FastAPI는 이 `response_model`를 사용하여: } ``` -!!! info "정보" - FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. +/// info | "정보" + +FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. + +/// -!!! info "정보" - 아래 또한 사용할 수 있습니다: +/// info | "정보" - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +아래 또한 사용할 수 있습니다: - Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + +/// #### 기본값이 있는 필드를 갖는 값의 데이터 @@ -166,10 +181,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: 따라서 JSON 스키마에 포함됩니다. -!!! tip "팁" - `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. +/// tip | "팁" + +`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. + +리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. - 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. +/// ### `response_model_include` 및 `response_model_exclude` @@ -179,21 +197,27 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. -!!! tip "팁" - 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. +/// tip | "팁" - 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. +하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. - 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. +이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. + +비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "팁" - 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. +/// tip | "팁" + +문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. + +이는 `set(["name", "description"])`과 동일합니다. - 이는 `set(["name", "description"])`과 동일합니다. +/// #### `set` 대신 `list` 사용하기 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index e6eed5120..48cb49cbf 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "참고" - `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. +/// note | "참고" + +`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. + +/// `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -!!! info "정보" - `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. +/// info | "정보" + +`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. + +/// `status_code` 매개변수는: @@ -27,15 +33,21 @@ -!!! note "참고" - 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). +/// note | "참고" + +어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). + +이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. - 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. +/// ## HTTP 상태 코드에 대하여 -!!! note "참고" - 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. +/// note | "참고" + +만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. + +/// HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다. @@ -54,8 +66,11 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. * `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. -!!! tip "팁" - 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. +/// tip | "팁" + +각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. + +/// ## 이름을 기억하는 쉬운 방법 @@ -79,10 +94,13 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 -!!! note "기술적 세부사항" - `from starlette import status` 역시 사용할 수 있습니다. +/// note | "기술적 세부사항" + +`from starlette import status` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. +/// ## 기본값 변경 diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 4e319e075..7b5ccdd32 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -8,71 +8,93 @@ 생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. -=== "Python 3.10+ Pydantic v2" +//// tab | Python 3.10+ Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-24" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Python 3.10+ Pydantic v1 -=== "Python 3.8+ Pydantic v2" +```Python hl_lines="13-23" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +``` - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +//// tab | Python 3.8+ Pydantic v2 - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +```Python hl_lines="15-26" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// + +//// tab | Python 3.8+ Pydantic v1 + +```Python hl_lines="15-25" +{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +``` + +//// 추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. -=== "Pydantic v2" +//// tab | Pydantic v2 + +Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. + +`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. +//// - `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// tab | Pydantic v1 -=== "Pydantic v1" +Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. - Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. +`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// -!!! tip "팁" - JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. +/// tip | "팁" - 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. +JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. -!!! info "정보" - (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. +예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. - 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 +/// - 이 문서 끝에 더 많은 읽을거리가 있습니다. +/// info | "정보" + +(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. + +그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 + +이 문서 끝에 더 많은 읽을거리가 있습니다. + +/// ## `Field` 추가 인자 Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// ## JSON Schema에서의 `examples` - OpenAPI @@ -92,41 +114,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="22-29" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="23-30" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="18-25" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="20-27" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### 문서 UI 예시 @@ -138,41 +176,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 물론 여러 `examples`를 넘길 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +```Python hl_lines="23-38" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24-39" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="19-34" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | "팁" + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="21-36" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// 이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. @@ -213,41 +267,57 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 이를 다음과 같이 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.10+ Annotated가 없는 경우 -=== "Python 3.8+" +/// tip | "팁" - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.10+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +``` - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.8+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | "팁" - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +``` + +//// ### 문서 UI에서의 OpenAPI 예시 @@ -257,17 +327,23 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 ## 기술적 세부 사항 -!!! tip "팁" - 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. +/// tip | "팁" + +이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. + +세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. + +간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 - 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. +/// - 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 +/// warning | "경고" -!!! warning "경고" - 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. +표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. - 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. +만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. + +/// OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다. @@ -285,8 +361,11 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 * `File()` * `Form()` -!!! info "정보" - 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. +/// info | "정보" + +이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. + +/// ### JSON 스키마의 `examples` 필드 @@ -298,10 +377,13 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. -!!! info "정보" - 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). +/// info | "정보" + +더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). + +이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. - 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. +/// ### Pydantic과 FastAPI `examples` diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index f4b6f9471..9bf3d4ee1 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -16,17 +16,21 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="3 10-14" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## `get_current_user` 의존성 생성하기 @@ -38,63 +42,81 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="25" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="23" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="19-22 26-27" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17-20 24-25" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="29" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. 이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. -!!! tip "팁" - 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. +/// tip | "팁" + +요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. + +여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. - 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. +/// -!!! check "확인" - 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. +/// check | "확인" - 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. +이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. + +해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. + +/// ## 다른 모델 @@ -128,17 +150,21 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="30-32" +{!> ../../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="28-30" +{!> ../../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index 1e33f5766..9593f96f5 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `instagram_basic`은 페이스북/인스타그램에서 사용합니다. * `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. -!!! 정보 - OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. +/// 정보 - `:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. +OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. - 이러한 세부 사항은 구현에 따라 다릅니다. +`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. - OAuth2의 경우 문자열일 뿐입니다. +이러한 세부 사항은 구현에 따라 다릅니다. + +OAuth2의 경우 문자열일 뿐입니다. + +/// ## `username`과 `password`를 가져오는 코드 @@ -49,17 +52,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="4 76" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "파이썬 3.10 이상" +//// - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="2 74" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// `OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: @@ -68,29 +75,38 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. * `grant_type`(선택적으로 사용). -!!! 팁 - OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. +/// 팁 + +OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. - 사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. +사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. + +/// * `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). * `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). -!!! 정보 - `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. +/// 정보 + +`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. - `OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. +`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. - 그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. +그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. - 그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. +그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. + +/// ### 폼 데이터 사용하기 -!!! 팁 - 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. +/// 팁 + +종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. + +이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. - 이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. +/// 이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다. @@ -98,17 +114,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 오류의 경우 `HTTPException` 예외를 사용합니다: -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="3 77-79" +{!> ../../../docs_src/security/tutorial003.py!} +``` -=== "파이썬 3.10 이상" +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="1 75-77" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` + +//// ### 패스워드 확인하기 @@ -134,17 +154,21 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). -=== "P파이썬 3.7 이상" +//// tab | P파이썬 3.7 이상 + +```Python hl_lines="80-83" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="78-81" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// #### `**user_dict`에 대해 @@ -162,8 +186,11 @@ UserInDB( ) ``` -!!! 정보 - `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. +/// 정보 + +`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. + +/// ## 토큰 반환하기 @@ -175,31 +202,41 @@ UserInDB( 이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. -!!! 팁 - 다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. +/// 팁 + +다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. + +하지만 지금은 필요한 세부 정보에 집중하겠습니다. + +/// + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="85" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// - 하지만 지금은 필요한 세부 정보에 집중하겠습니다. +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.7 이상" +```Python hl_lines="83" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +/// 팁 - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. -!!! 팁 - 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. +이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. - 이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. +사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. - 사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. +나머지는 **FastAPI**가 처리합니다. - 나머지는 **FastAPI**가 처리합니다. +/// ## 의존성 업데이트하기 @@ -213,32 +250,39 @@ UserInDB( 따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="58-66 69-72 90" +{!> ../../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="55-64 67-70 88" +{!> ../../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +/// 정보 - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. -!!! 정보 - 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. +모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. - 모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. +베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. - 베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. +실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. - 실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. +그러나 여기에서는 사양을 준수하도록 제공됩니다. - 그러나 여기에서는 사양을 준수하도록 제공됩니다. +또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. - 또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. +그것이 표준의 이점입니다 ... - 그것이 표준의 이점입니다 ... +/// ## 확인하기 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index fe1aa4e5e..360aaaa6b 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "기술적 세부사항" - `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. +/// note | "기술적 세부사항" - **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. +`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. + +**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. + +/// ### "마운팅" 이란 diff --git a/docs/missing-translation.md b/docs/missing-translation.md index 32b6016f9..c2882e90e 100644 --- a/docs/missing-translation.md +++ b/docs/missing-translation.md @@ -1,4 +1,7 @@ -!!! warning - The current page still doesn't have a translation for this language. +/// warning - But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. +The current page still doesn't have a translation for this language. + +But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. + +/// diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index a6435977c..80d3bdece 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` oznacza: +/// info - Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` oznacza: + +Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Wsparcie edytora diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 00c99edfa..4daad5e90 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -170,12 +170,15 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa * Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś. -!!! info - Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. +/// info - Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 +Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. - Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 +Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 + +Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 + +/// * Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach. @@ -226,10 +229,13 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. -!!! tip "Wskazówka" - Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. +/// tip | "Wskazówka" + +Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Używaj czatu tylko do innych ogólnych rozmów. - Używaj czatu tylko do innych ogólnych rozmów. +/// ### Nie zadawaj pytań na czacie diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index ce71f8b83..8f1b9b922 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note - Polecenie `uvicorn main:app` odnosi się do: +/// note - * `main`: plik `main.py` ("moduł" Python). - * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. - * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. +Polecenie `uvicorn main:app` odnosi się do: + +* `main`: plik `main.py` ("moduł" Python). +* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. +* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. + +/// Na wyjściu znajduje się linia z czymś w rodzaju: @@ -136,11 +139,13 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -!!! note "Szczegóły techniczne" - `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. +/// note | "Szczegóły techniczne" + +`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. - Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +/// ### Krok 2: utwórz instancję `FastAPI` @@ -200,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. +/// info + +"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. + +/// Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”. @@ -251,16 +259,19 @@ Będziemy je również nazywali "**operacjami**". * ścieżki `/` * używając operacji get -!!! info "`@decorator` Info" - Składnia `@something` jest w Pythonie nazywana "dekoratorem". +/// info | "`@decorator` Info" + +Składnia `@something` jest w Pythonie nazywana "dekoratorem". - Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). +Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). - "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. +"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. - W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. +W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. - Jest to "**dekorator operacji na ścieżce**". +Jest to "**dekorator operacji na ścieżce**". + +/// Możesz również użyć innej operacji: @@ -275,14 +286,17 @@ Oraz tych bardziej egzotycznych: * `@app.patch()` * `@app.trace()` -!!! tip - Możesz dowolnie używać każdej operacji (metody HTTP). +/// tip + +Możesz dowolnie używać każdej operacji (metody HTTP). + +**FastAPI** nie narzuca żadnego konkretnego znaczenia. - **FastAPI** nie narzuca żadnego konkretnego znaczenia. +Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. - Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. +Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. - Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. +/// ### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę** @@ -310,8 +324,11 @@ Możesz również zdefiniować to jako normalną funkcję zamiast `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Krok 5: zwróć zawartość diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md index f8c5c6022..66f7c6d62 100644 --- a/docs/pl/docs/tutorial/index.md +++ b/docs/pl/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod. -!!! note - Możesz również wykonać instalację "krok po kroku". +/// note - Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: +Możesz również wykonać instalację "krok po kroku". - ``` - pip install fastapi - ``` +Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: - Zainstaluj też `uvicorn`, który będzie służył jako serwer: +``` +pip install fastapi +``` + +Zainstaluj też `uvicorn`, który będzie służył jako serwer: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. - Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. +/// ## Zaawansowany poradnik diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 7c7d22611..c27301b61 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Retornos Adicionais no OpenAPI -!!! warning "Aviso" - Este é um tema bem avançado. +/// warning | "Aviso" - Se você está começando com o **FastAPI**, provavelmente você não precisa disso. +Este é um tema bem avançado. + +Se você está começando com o **FastAPI**, provavelmente você não precisa disso. + +/// Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc. @@ -27,20 +30,26 @@ Por exemplo, para declarar um outro retorno com o status code `404` e um modelo {!../../../docs_src/additional_responses/tutorial001.py!} ``` -!!! note "Nota" - Lembre-se que você deve retornar o `JSONResponse` diretamente. +/// note | "Nota" + +Lembre-se que você deve retornar o `JSONResponse` diretamente. + +/// + +/// info | "Informação" -!!! info "Informação" - A chave `model` não é parte do OpenAPI. +A chave `model` não é parte do OpenAPI. - O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. +O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. - O local correto é: +O local correto é: - * Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: - * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: - * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. - * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. +* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: + * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: + * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. + * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. + +/// O retorno gerado no OpenAI para esta *operação de caminho* será: @@ -172,13 +181,19 @@ Por exemplo, você pode adicionar um media type adicional de `image/png`, declar {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! note "Nota" - Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. +/// note | "Nota" + +Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. + +/// + +/// info | "Informação" + +A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). -!!! info "Informação" - A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). +Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. - Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. +/// ## Combinando informações diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index a7699b324..a0869f342 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "Dica" - Faça uso da versão `Annotated` quando possível. +```Python hl_lines="4 26" +{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip "Dica" - Faça uso da versão `Annotated` quando possível. +/// tip | "Dica" - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Faça uso da versão `Annotated` quando possível. -!!! warning "Aviso" - Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. +/// - Ele não será serializado com um modelo, etc. +```Python hl_lines="2 23" +{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). +//// -!!! note "Detalhes técnicos" - Você também pode utilizar `from starlette.responses import JSONResponse`. +//// tab | Python 3.8+ non-Annotated - O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. +/// tip | "Dica" + +Faça uso da versão `Annotated` quando possível. + +/// + +```Python hl_lines="4 25" +{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | "Aviso" + +Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. + +Ele não será serializado com um modelo, etc. + +Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). + +/// + +/// note | "Detalhes técnicos" + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. + +/// ## OpenAPI e documentação da API diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 58887f9c8..5a7b921b2 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla Para fazer isso, nós declaramos o método `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +Prefira utilizar a versão `Annotated` se possível. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. @@ -45,26 +54,35 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +Prefira utilizar a versão `Annotated` se possível. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. @@ -72,26 +90,35 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós Nós poderíamos criar uma instância desta classe com: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` + +//// E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Prefira utilizar a versão `Annotated` se possível. +/// tip | "Dica" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. -!!! tip "Dica" - Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. +Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. - Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. +Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. - Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. +Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. - Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. +/// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 4ccc0c452..ab5bfa648 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -64,8 +64,11 @@ O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste dev {!../../../docs_src/async_tests/test_main.py!} ``` -!!! tip "Dica" - Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. +/// tip | "Dica" + +Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. + +/// Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. @@ -81,15 +84,24 @@ response = client.get('/') ...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. -!!! tip "Dica" - Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. +/// tip | "Dica" + +Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. + +/// -!!! warning "Aviso" - Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. +/// warning | "Aviso" + +Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. + +/// ## Outras Chamadas de Funções Assíncronas Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. -!!! tip "Dica" - Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. +/// tip | "Dica" + +Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. + +/// diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 8ac9102a3..2dfc5ca25 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip "Dica" - O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. +/// tip | "Dica" + +O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. + +/// A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo: @@ -81,10 +84,13 @@ $ fastapi run main.py --root-path /api/v1 Se você usar Hypercorn, ele também tem a opção `--root-path`. -!!! note "Detalhes Técnicos" - A especificação ASGI define um `root_path` para esse caso de uso. +/// note | "Detalhes Técnicos" + +A especificação ASGI define um `root_path` para esse caso de uso. + +E a opção de linha de comando `--root-path` fornece esse `root_path`. - E a opção de linha de comando `--root-path` fornece esse `root_path`. +/// ### Verificando o `root_path` atual @@ -172,8 +178,11 @@ Então, crie um arquivo `traefik.toml` com: Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. -!!! tip "Dica" - Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). +/// tip | "Dica" + +Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). + +/// Agora crie esse outro arquivo `routes.toml`: @@ -239,8 +248,11 @@ Agora, se você for ao URL com a porta para o Uvicorn: http://127.0.0.1:9999/api/v1/app. @@ -283,8 +295,11 @@ Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no Open ## Servidores adicionais -!!! warning "Aviso" - Este é um caso de uso mais avançado. Sinta-se à vontade para pular. +/// warning | "Aviso" + +Este é um caso de uso mais avançado. Sinta-se à vontade para pular. + +/// Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`. @@ -323,15 +338,21 @@ Gerará um OpenAPI schema como: } ``` -!!! tip "Dica" - Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. +/// tip | "Dica" + +Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. + +/// Na interface de documentação em http://127.0.0.1:9999/api/v1/docs parecerá: -!!! tip "Dica" - A interface de documentação interagirá com o servidor que você selecionar. +/// tip | "Dica" + +A interface de documentação interagirá com o servidor que você selecionar. + +/// ### Desabilitar servidor automático de `root_path` diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 12aa93f29..5f722763e 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -39,10 +39,13 @@ Aqui nós estamos simulando a *inicialização* custosa do carregamento do model E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -!!! tip "Dica" - O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. +/// tip | "Dica" - Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 +O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. + +Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 + +/// ### Função _lifespan_ @@ -92,10 +95,13 @@ O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Context ## Eventos alternativos (deprecados) -!!! warning "Aviso" - A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. +/// warning | "Aviso" + +A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. - Você provavelmente pode pular essa parte. +Você provavelmente pode pular essa parte. + +/// Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*. @@ -127,17 +133,23 @@ Para adicionar uma função que deve ser executada quando a aplicação estiver Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -!!! info "Informação" - Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. +/// info | "Informação" + +Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. -!!! tip "Dica" - Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. +/// - Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. +/// tip | "Dica" - Mas `open()` não usa `async` e `await`. +Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. - Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. +Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. + +Mas `open()` não usa `async` e `await`. + +Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. + +/// ### `startup` e `shutdown` juntos @@ -153,10 +165,13 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`. -!!! info "Informação" - Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. +/// info | "Informação" + +Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. + +Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. - Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. +/// ## Sub Aplicações diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 413d8815f..2569fc914 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -6,10 +6,13 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla Na próxima seção você verá outras opções, configurações, e recursos adicionais. -!!! tip "Dica" - As próximas seções **não são necessáriamente "avançadas"** +/// tip | "Dica" - E é possível que para seu caso de uso, a solução esteja em uma delas. +As próximas seções **não são necessáriamente "avançadas"** + +E é possível que para seu caso de uso, a solução esteja em uma delas. + +/// ## Leia o Tutorial primeiro diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 932fe0d9a..2ccd0e819 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -22,8 +22,11 @@ Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webh Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. -!!! info "Informação" - Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. +/// info | "Informação" + +Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. + +/// ## Uma aplicação com webhooks @@ -35,8 +38,11 @@ Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. -!!! info "Informação" - O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. +/// info | "Informação" + +O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. + +/// Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`. diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index f6962831f..db2b4c9cc 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -8,44 +8,51 @@ Por isso é comum prover essas configurações como variáveis de ambiente que s ## Variáveis de Ambiente -!!! dica - Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. +/// dica + +Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. + +/// Uma variável de ambiente (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas). Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - // Você pode criar uma env var MY_NAME usando - $ export MY_NAME="Wade Wilson" +```console +// Você pode criar uma env var MY_NAME usando +$ export MY_NAME="Wade Wilson" - // E utilizá-la em outros programas, como - $ echo "Hello $MY_NAME" +// E utilizá-la em outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// Criando env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Criando env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Usando em outros programas, como +$ echo "Hello $Env:MY_NAME" - // Usando em outros programas, como - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### Lendo variáveis de ambiente com Python @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! dica - O segundo parâmetro em `os.getenv()` é o valor padrão para o retorno. +/// dica + +O segundo parâmetro em `os.getenv()` é o valor padrão para o retorno. - Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. +Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. + +/// E depois você pode executar esse arquivo: @@ -114,8 +124,11 @@ Hello World from Python -!!! dica - Você pode ler mais sobre isso em: The Twelve-Factor App: Configurações. +/// dica + +Você pode ler mais sobre isso em: The Twelve-Factor App: Configurações. + +/// ### Tipagem e Validação @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" -!!! info - Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. +/// info + +Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. + +/// ### Criando o objeto `Settings` @@ -162,23 +178,33 @@ Os atributos da classe são declarados com anotações de tipo, e possíveis val Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! Info - Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. +/// dica - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. -!!! dica - Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. +/// Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`. @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p -!!! dica - Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. +/// dica + +Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. + +/// Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`. @@ -231,8 +260,11 @@ E utilizar essa configuração em `main.py`: {!../../../docs_src/settings/app01/main.py!} ``` -!!! dica - Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. +/// dica + +Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +/// ## Configurações em uma dependência @@ -254,54 +286,75 @@ Perceba que dessa vez não criamos uma instância padrão `settings = Settings() Agora criamos a dependência que retorna um novo objeto `config.Settings()`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! dica - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// dica -!!! dica - Vamos discutir sobre `@lru_cache` logo mais. +Utilize a versão com `Annotated` se possível. - Por enquanto, você pode considerar `get_settings()` como uma função normal. +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// + +/// dica + +Vamos discutir sobre `@lru_cache` logo mais. + +Por enquanto, você pode considerar `get_settings()` como uma função normal. + +/// E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// dica -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! dica - Utilize a versão com `Annotated` se possível. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` + +//// ### Configurações e testes @@ -321,15 +374,21 @@ Se você tiver muitas configurações que variem bastante, talvez em ambientes d Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". -!!! dica - Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. +/// dica + +Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. - Mas um arquivo dotenv não precisa ter esse nome exato. +Mas um arquivo dotenv não precisa ter esse nome exato. + +/// Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em Pydantic Settings: Dotenv (.env) support. -!!! dica - Para que isso funcione você precisa executar `pip install python-dotenv`. +/// dica + +Para que isso funcione você precisa executar `pip install python-dotenv`. + +/// ### O arquivo `.env` @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" E então adicionar o seguinte código em `config.py`: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/settings/app03_an/config.py!} +``` - !!! dica - O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. +/// dica -=== "Pydantic v1" +O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! dica - A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. +//// -!!! info - Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// dica + +A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +/// + +//// + +/// info + +Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. + +/// Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar. @@ -390,26 +462,35 @@ Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// dica -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! dica - Utilize a versão com `Annotated` se possível. +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 3bada5e43..6d231b3c2 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -29,20 +29,27 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note - Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +/// note - Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. +Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. -!!! tip "Dica" - Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. +/// +/// tip | "Dica" -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette.templating import Jinja2Templates`. +Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. - **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. +/// + +/// note | "Detalhes Técnicos" + +Você também poderia usar `from starlette.templating import Jinja2Templates`. + +**FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +/// ## Escrevendo Templates diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 0e79c4f77..d3a304fa7 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -30,11 +30,17 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -!!! note "Nota" - Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. +/// note | "Nota" -!!! check "**FastAPI** inspirado para" - Ter uma documentação automática da API em interface web. +Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. + +/// + +/// check | "**FastAPI** inspirado para" + +Ter uma documentação automática da API em interface web. + +/// ### Flask @@ -50,10 +56,13 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -!!! check "**FastAPI** inspirado para" - Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. +/// check | "**FastAPI** inspirado para" - Ser simples e com sistema de roteamento fácil de usar. +Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. + +Ser simples e com sistema de roteamento fácil de usar. + +/// ### Requests @@ -89,10 +98,13 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -!!! check "**FastAPI** inspirado para" - * Ter uma API simples e intuitiva. - * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. - * Ter padrões sensíveis, mas customizações poderosas. +/// check | "**FastAPI** inspirado para" + +* Ter uma API simples e intuitiva. +* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. +* Ter padrões sensíveis, mas customizações poderosas. + +/// ### Swagger / OpenAPI @@ -106,15 +118,18 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -!!! check "**FastAPI** inspirado para" - Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. +/// check | "**FastAPI** inspirado para" + +Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. + +E integrar ferramentas de interface para usuários baseado nos padrões: - E integrar ferramentas de interface para usuários baseado nos padrões: +* Swagger UI +* ReDoc - * Swagger UI - * ReDoc +Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). - Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). +/// ### Flask REST frameworks @@ -132,8 +147,11 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -!!! check "**FastAPI** inspirado para" - Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. +/// check | "**FastAPI** inspirado para" + +Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. + +/// ### Webargs @@ -145,11 +163,17 @@ Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pe Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**. -!!! info - Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. -!!! check "**FastAPI** inspirado para" - Ter validação automática de dados vindos de requisições. +/// + +/// check | "**FastAPI** inspirado para" + +Ter validação automática de dados vindos de requisições. + +/// ### APISpec @@ -169,11 +193,17 @@ Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto. -!!! info - APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// + +/// check | "**FastAPI** inspirado para" -!!! check "**FastAPI** inspirado para" - Dar suporte a padrões abertos para APIs, OpenAPI. +Dar suporte a padrões abertos para APIs, OpenAPI. + +/// ### Flask-apispec @@ -195,11 +225,17 @@ Usando essa combinação levou a criação de vários geradores Flask _full-stac E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// -!!! check "**FastAPI** inspirado para" - Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. +/// check | "**FastAPI** inspirado para" + +Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. + +/// ### NestJS (and Angular) @@ -215,24 +251,33 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -!!! check "**FastAPI** inspirado para" - Usar tipos Python para ter um ótimo suporte do editor. +/// check | "**FastAPI** inspirado para" + +Usar tipos Python para ter um ótimo suporte do editor. - Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. +Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. + +/// ### Sanic Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -!!! note "Detalhes técnicos" - Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. +/// note | "Detalhes técnicos" + +Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. + +Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. + +/// - Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. +/// check | "**FastAPI** inspirado para" -!!! check "**FastAPI** inspirado para" - Achar um jeito de ter uma performance insana. +Achar um jeito de ter uma performance insana. - É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). +É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). + +/// ### Falcon @@ -244,12 +289,15 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -!!! check "**FastAPI** inspirado para" - Achar jeitos de conseguir melhor performance. +/// check | "**FastAPI** inspirado para" + +Achar jeitos de conseguir melhor performance. + +Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. - Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. +Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. - Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. +/// ### Molten @@ -267,10 +315,13 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -!!! check "**FastAPI** inspirado para" - Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. +/// check | "**FastAPI** inspirado para" - Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). +Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. + +Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). + +/// ### Hug @@ -286,15 +337,21 @@ Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possív Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também. -!!! info - Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. +/// info + +Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. + +/// + +/// check | "Idéias inspiradas para o **FastAPI**" + +Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. -!!! check "Idéias inspiradas para o **FastAPI**" - Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. +Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. - Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. +Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. - Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. +/// ### APIStar (<= 0.5) @@ -320,23 +377,29 @@ Ele não era mais um framework web API, como o criador precisava focar no Starle Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web. -!!! info - APIStar foi criado por Tom Christie. O mesmo cara que criou: +/// info - * Django REST Framework - * Starlette (no qual **FastAPI** é baseado) - * Uvicorn (usado por Starlette e **FastAPI**) +APIStar foi criado por Tom Christie. O mesmo cara que criou: -!!! check "**FastAPI** inspirado para" - Existir. +* Django REST Framework +* Starlette (no qual **FastAPI** é baseado) +* Uvicorn (usado por Starlette e **FastAPI**) - A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. +/// - E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. +/// check | "**FastAPI** inspirado para" - Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. +Existir. - Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. +A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. + +E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. + +Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. + +Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. + +/// ## Usados por **FastAPI** @@ -348,10 +411,13 @@ Isso faz dele extremamente intuitivo. Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo. -!!! check "**FastAPI** usa isso para" - Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). +/// check | "**FastAPI** usa isso para" + +Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). + +**FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. - **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. +/// ### Starlette @@ -381,17 +447,23 @@ Mas ele não fornece validação de dados automática, serialização e document Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc. -!!! note "Detalhes Técnicos" - ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. +/// note | "Detalhes Técnicos" - No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. +ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. -!!! check "**FastAPI** usa isso para" - Controlar todas as partes web centrais. Adiciona recursos no topo. +No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. - A classe `FastAPI` em si herda `Starlette`. +/// - Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. +/// check | "**FastAPI** usa isso para" + +Controlar todas as partes web centrais. Adiciona recursos no topo. + +A classe `FastAPI` em si herda `Starlette`. + +Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. + +/// ### Uvicorn @@ -401,12 +473,15 @@ Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece Ele é o servidor recomendado para Starlette e **FastAPI**. -!!! check "**FastAPI** recomenda isso para" - O principal servidor web para rodar aplicações **FastAPI**. +/// check | "**FastAPI** recomenda isso para" + +O principal servidor web para rodar aplicações **FastAPI**. + +Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. - Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. +Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. - Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Performance e velocidade diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index 1ec8f07c6..0d6bdbf0e 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Você só pode usar `await` dentro de funções criadas com `async def`. +/// note + +Você só pode usar `await` dentro de funções criadas com `async def`. + +/// --- @@ -356,12 +359,15 @@ Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ## Detalhes muito técnicos -!!! warning - Você pode provavelmente pular isso. +/// warning + +Você pode provavelmente pular isso. + +Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. - Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. +Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. - Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. +/// ### Funções de operação de rota diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md index 7d8d1fd5e..bb518a2fa 100644 --- a/docs/pt/docs/contributing.md +++ b/docs/pt/docs/contributing.md @@ -24,72 +24,85 @@ Isso criará o diretório `./env/` com os binários Python e então você será Ative o novo ambiente com: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
- Ou se você usa Bash para Windows (por exemplo Git Bash): +//// -
+//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +Ou se você usa Bash para Windows (por exemplo Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` + +
+ +//// Para verificar se funcionou, use: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip -
+some/directory/fastapi/env/bin/pip +``` + +
+ +//// Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 -!!! tip - Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. +/// tip + +Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. +Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. + +/// ### pip @@ -153,8 +166,11 @@ A documentação usa _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. -!!! tip - Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. +/// tip + +Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. + +Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. - Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. +/// * Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. @@ -264,8 +283,11 @@ Vamos dizer que você queira traduzir uma página para uma linguagem que já ten No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. -!!! tip - A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. +/// tip + +A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. + +/// Agora rode o _servidor ao vivo_ para as documentações em Espanhol: @@ -302,8 +324,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. +/// tip + +Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. + +/// * Agora abra o arquivo de configuração MkDocs para Inglês em: @@ -374,10 +399,13 @@ Updating en Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. -!!! tip - Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. +/// tip + +Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. + +Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 +/// Inicie traduzindo a página principal, `docs/ht/index.md`. diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md index d25ea79fd..6874a2529 100644 --- a/docs/pt/docs/deployment.md +++ b/docs/pt/docs/deployment.md @@ -50,8 +50,11 @@ Seguindo as convenções do Versionamento Semântico, qualquer versão abaixo de FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação. -!!! tip - O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. +/// tip + +O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. + +/// Então, você poderia ser capaz de fixar para uma versão como: @@ -61,8 +64,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_. -!!! tip - O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. +/// tip + +O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. + +/// ### Atualizando as versões FastAPI @@ -113,8 +119,11 @@ Essa imagem tem um mecanismo incluído de "auto-ajuste", para que você possa ap Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem do Docker: tiangolo/uvicorn-gunicorn-fastapi. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem do Docker: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Crie um `Dockerfile` @@ -248,8 +257,11 @@ Você verá a documentação automática alternativa (fornecida por https://howhttps.works/. @@ -329,61 +341,69 @@ Você pode fazer o _deploy_ do **FastAPI** diretamente sem o Docker também. Você apenas precisa instalar um servidor ASGI compatível como: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, um servidor ASGI peso leve, construído sobre uvloop e httptools. +* Uvicorn, um servidor ASGI peso leve, construído sobre uvloop e httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +//// -
+//// tab | Hypercorn -=== "Hypercorn" +* Hypercorn, um servidor ASGI também compatível com HTTP/2. - * Hypercorn, um servidor ASGI também compatível com HTTP/2. +
-
+```console +$ pip install hypercorn - ```console - $ pip install hypercorn +---> 100% +``` - ---> 100% - ``` +
-
+...ou qualquer outro servidor ASGI. - ...ou qualquer outro servidor ASGI. +//// E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +```console +$ hypercorn main:app --bind 0.0.0.0:80 - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
-
+//// Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar. diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index 9ab8d38f0..fa1a6b9c2 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,9 +4,11 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -!!! tip "Dica" - Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). +/// tip | "Dica" +Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). + +///
Visualização do Dockerfile 👀 @@ -131,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - Há outros formatos e ferramentas para definir e instalar dependências de pacote. +/// info + +Há outros formatos e ferramentas para definir e instalar dependências de pacote. + +Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 - Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 +/// ### Criando o Código do **FastAPI** @@ -223,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Porque o programa será iniciado em `/code` e dentro dele está o diretório `./app` com seu código, o **Uvicorn** será capaz de ver e **importar** `app` de `app.main`. -!!! tip - Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 +/// tip + +Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 + +/// Agora você deve ter uma estrutura de diretório como: @@ -294,10 +302,13 @@ $ docker build -t myimage . -!!! tip - Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. +/// tip - Nesse caso, é o mesmo diretório atual (`.`). +Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. + +Nesse caso, é o mesmo diretório atual (`.`). + +/// ### Inicie o contêiner Docker @@ -395,8 +406,11 @@ Se nos concentrarmos apenas na **imagem do contêiner** para um aplicativo FastA Isso poderia ser outro contêiner, por exemplo, com Traefik, lidando com **HTTPS** e aquisição **automática** de **certificados**. -!!! tip - Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. +/// tip + +Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. + +/// Alternativamente, o HTTPS poderia ser tratado por um provedor de nuvem como um de seus serviços (enquanto ainda executasse o aplicativo em um contêiner). @@ -424,8 +438,11 @@ Quando usando contêineres, normalmente você terá algum componente **escutando Como esse componente assumiria a **carga** de solicitações e distribuiria isso entre os trabalhadores de uma maneira (esperançosamente) **balanceada**, ele também é comumente chamado de **Balanceador de Carga**. -!!! tip - O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. +/// tip + +O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. + +/// E quando trabalhar com contêineres, o mesmo sistema que você usa para iniciar e gerenciá-los já terá ferramentas internas para transmitir a **comunicação de rede** (por exemplo, solicitações HTTP) do **balanceador de carga** (que também pode ser um **Proxy de Terminação TLS**) para o(s) contêiner(es) com seu aplicativo. @@ -504,8 +521,11 @@ Se você estiver usando contêineres (por exemplo, Docker, Kubernetes), existem Se você tiver **múltiplos contêineres**, provavelmente cada um executando um **único processo** (por exemplo, em um cluster do **Kubernetes**), então provavelmente você gostaria de ter um **contêiner separado** fazendo o trabalho dos **passos anteriores** em um único contêiner, executando um único processo, **antes** de executar os contêineres trabalhadores replicados. -!!! info - Se você estiver usando o Kubernetes, provavelmente será um Init Container. +/// info + +Se você estiver usando o Kubernetes, provavelmente será um Init Container. + +/// Se no seu caso de uso não houver problema em executar esses passos anteriores **em paralelo várias vezes** (por exemplo, se você não estiver executando migrações de banco de dados, mas apenas verificando se o banco de dados está pronto), então você também pode colocá-los em cada contêiner logo antes de iniciar o processo principal. @@ -521,8 +541,11 @@ Essa imagem seria útil principalmente nas situações descritas acima em: [Cont * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). +/// warning + +Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). + +/// Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis. @@ -530,8 +553,11 @@ Isso tem **padrões sensíveis**, mas você ainda pode alterar e atualizar todas Há também suporte para executar **passos anteriores antes de iniciar** com um script. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Número de Processos na Imagem Oficial do Docker @@ -660,8 +686,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Execute o comando `uvicorn`, informando-o para usar o objeto `app` importado de `app.main`. -!!! tip - Clique nos números das bolhas para ver o que cada linha faz. +/// tip + +Clique nos números das bolhas para ver o que cada linha faz. + +/// Um **estágio do Docker** é uma parte de um `Dockerfile` que funciona como uma **imagem temporária do contêiner** que só é usada para gerar alguns arquivos para serem usados posteriormente. diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index f85861e92..6ccc875fd 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -4,8 +4,11 @@ Mas é bem mais complexo do que isso. -!!! tip "Dica" - Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. +/// tip | "Dica" + +Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. + +/// Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique https://howhttps.works/pt-br/. diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 77d9bab69..79243a014 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,8 +42,11 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -!!! tip "Dica" - O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. +/// tip | "Dica" + +O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. + +/// Logo, você deveria conseguir fixar a versão, como: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -!!! tip "Dica" - O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. +/// tip | "Dica" + +O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. + +/// ## Atualizando as versões do FastAPI diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md index a4832804d..622ad5ab6 100644 --- a/docs/pt/docs/external-links.md +++ b/docs/pt/docs/external-links.md @@ -6,8 +6,11 @@ Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **Fast Aqui tem uma lista, incompleta, de algumas delas. -!!! tip "Dica" - Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. +/// tip | "Dica" + +Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md index a4dfda660..829686631 100644 --- a/docs/pt/docs/fastapi-cli.md +++ b/docs/pt/docs/fastapi-cli.md @@ -80,5 +80,8 @@ Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endere Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo. -!!! tip - Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. +/// tip + +Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 64efeeae1..a90a8094b 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` quer dizer: +/// info - Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` quer dizer: + +Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Suporte de editores diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 0deef15b5..61eeac0dc 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -109,10 +109,13 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 server de conversa do Discord 👥 e conheça novas pessoas da comunidade do FastAPI. -!!! tip "Dica" - Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. +/// tip | "Dica" - Use o chat apenas para outro tipo de assunto. +Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. + +Use o chat apenas para outro tipo de assunto. + +/// ### Não faça perguntas no chat diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md index 664e89144..6747b01c7 100644 --- a/docs/pt/docs/how-to/index.md +++ b/docs/pt/docs/how-to/index.md @@ -6,6 +6,8 @@ A maioria dessas ideias será mais ou menos **independente**, e na maioria dos c Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo. -!!! tip +/// tip - Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. +Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. + +/// diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 52b2dad8e..86630cd2a 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -12,9 +12,11 @@ O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e ben Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles. -!!! note "Nota" - Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. +/// note | "Nota" +Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. + +/// ## Motivação @@ -173,10 +175,13 @@ Como a lista é um tipo que contém alguns tipos internos, você os coloca entre {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Dica" - Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". +/// tip | "Dica" + +Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". - Nesse caso, `str` é o parâmetro de tipo passado para `List`. +Nesse caso, `str` é o parâmetro de tipo passado para `List`. + +/// Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". @@ -282,8 +287,11 @@ Retirado dos documentos oficiais dos Pydantic: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info "Informação" - Para saber mais sobre o Pydantic, verifique seus documentos . +/// info | "Informação" + +Para saber mais sobre o Pydantic, verifique seus documentos . + +/// **FastAPI** é todo baseado em Pydantic. @@ -311,5 +319,8 @@ Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em aç O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você. -!!! info "Informação" - Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . +/// info | "Informação" + +Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . + +/// diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index 8f3313ae9..cce37cd55 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -10,8 +10,11 @@ Primeiro, você tem que importá-lo: {!../../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "Aviso" - Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). +/// warning | "Aviso" + +Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). + +/// ## Declare atributos do modelo @@ -23,17 +26,23 @@ Você pode então utilizar `Field` com atributos do modelo: `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -!!! note "Detalhes técnicos" - Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. +/// note | "Detalhes técnicos" + +Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. + +E `Field` do Pydantic retorna uma instância de `FieldInfo` também. + +`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. + +Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. - E `Field` do Pydantic retorna uma instância de `FieldInfo` também. +/// - `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. +/// tip | "Dica" - Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. +Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. -!!! tip "Dica" - Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. +/// ## Adicione informações extras diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 7d0435a6b..d36dd60b3 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +//// -!!! note "Nota" - Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. +/// note | "Nota" + +Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. + +/// ## Múltiplos parâmetros de corpo @@ -38,17 +45,21 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -69,9 +80,11 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -!!! note "Nota" - Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. +/// note | "Nota" +Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. + +/// O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`. @@ -87,17 +100,21 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "Python 3.10+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// Neste caso, o **FastAPI** esperará um corpo como: @@ -137,20 +154,27 @@ q: str | None = None Por exemplo: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="26" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// -=== "Python 3.8+" +/// info | "Informação" - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. -!!! info "Informação" - `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. +/// ## Declare um único parâmetro de corpo indicando sua chave @@ -166,17 +190,21 @@ item: Item = Body(embed=True) como em: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` + +//// - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index c9d0b8bb6..7d933b27f 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -165,8 +165,11 @@ Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual: } ``` -!!! info "informação" - Note como o campo `images` agora tem uma lista de objetos de image. +/// info | "informação" + +Note como o campo `images` agora tem uma lista de objetos de image. + +/// ## Modelos profundamente aninhados @@ -176,8 +179,11 @@ Você pode definir modelos profundamente aninhados de forma arbitrária: {!../../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "informação" - Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s +/// info | "informação" + +Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s + +/// ## Corpos de listas puras @@ -226,14 +232,17 @@ Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com va {!../../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "Dica" - Leve em condideração que o JSON só suporta `str` como chaves. +/// tip | "Dica" + +Leve em condideração que o JSON só suporta `str` como chaves. + +Mas o Pydantic tem conversão automática de dados. - Mas o Pydantic tem conversão automática de dados. +Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. - Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. +E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. - E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. +/// ## Recapitulação diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 713bea2d1..f67687fb5 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -8,12 +8,15 @@ Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. -!!! info "Informação" - Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. +/// info | "Informação" - Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. +Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. - Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. +Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. + +Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. + +/// ## Importe o `BaseModel` do Pydantic @@ -110,16 +113,19 @@ Mas você terá o mesmo suporte do editor no -!!! tip "Dica" - Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . +/// tip | "Dica" + +Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . - Melhora o suporte do editor para seus modelos Pydantic com:: +Melhora o suporte do editor para seus modelos Pydantic com:: - * completação automática - * verificação de tipos - * refatoração - * buscas - * inspeções +* completação automática +* verificação de tipos +* refatoração +* buscas +* inspeções + +/// ## Use o modelo @@ -155,10 +161,13 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | "Observação" + +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. - O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. +/// ## Sem o Pydantic diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 1a60e3571..caed17632 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -20,13 +20,19 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi {!../../../docs_src/cookie_params/tutorial001.py!} ``` -!!! note "Detalhes Técnicos" - `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. +/// note | "Detalhes Técnicos" - Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +`Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. -!!! info "Informação" - Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. + +/// + +/// info | "Informação" + +Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. + +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 1f434d324..e5e2f8c27 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware pass Para mais informações CORS, acesse Mozilla CORS documentation. -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Detalhes técnicos" - **FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. +Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 028bf3d20..420503b87 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. @@ -103,123 +119,165 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Observe o método `__init__` usado para criar uma instância da classe: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Dica" - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Utilize a versão com `Annotated` se possível. -=== "Python 3.10+ non-Annotated" +/// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. @@ -235,43 +293,57 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc Agora você pode declarar sua dependência utilizando essa classe. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. @@ -279,21 +351,27 @@ O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" des Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. +/// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// O último `CommonQueryParams`, em: @@ -309,81 +387,107 @@ O último `CommonQueryParams`, em: Nesse caso, o primeiro `CommonQueryParams`, em: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +```Python +commons: Annotated[CommonQueryParams, ... +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// tab | Python 3.8+ non-Annotated +/// tip | "Dica" - ```Python - commons: CommonQueryParams ... - ``` +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso). Na verdade você poderia escrever apenas: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python +commons = Depends(CommonQueryParams) +``` - ```Python - commons = Depends(CommonQueryParams) - ``` +//// ...como em: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. @@ -393,20 +497,27 @@ Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto s Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +Utilize a versão com `Annotated` se possível. - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe. @@ -414,84 +525,114 @@ Para esses casos específicos, você pode fazer o seguinte: Em vez de escrever: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...escreva: -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +//// -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// tip | "Dica" +Utilize a versão com `Annotated` se possível. - ```Python - commons: CommonQueryParams = Depends() - ``` +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`. O mesmo exemplo ficaria então dessa forma: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+" +Utilize a versão com `Annotated` se possível. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +//// +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +/// tip | "Dica" -=== "Python 3.8+ non-Annotated" +Utilize a versão com `Annotated` se possível. - !!! tip "Dica" - Utilize a versão com `Annotated` se possível. +/// +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// ...e o **FastAPI** saberá o que fazer. -!!! tip "Dica" - Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. +/// tip | "Dica" + +Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. + +É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. - É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. +/// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4a297268c..4a7a29390 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,39 +14,55 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`. Ele deve ser uma lista de `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | "Dica" + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. -!!! tip "Dica" - Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. +/// tip | "Dica" + +Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. - Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. +Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. - Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. +Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. -!!! info "Informação" - Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. +/// - Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. +/// info | "Informação" + +Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. + +Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// ## Erros das dependências e valores de retorno @@ -56,51 +72,69 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 non-Annotated - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | "Dica" -=== "Python 3.8 non-Annotated" +Utilize a versão com `Annotated` se possível - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +/// - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Levantando exceções Essas dependências podem levantar exceções, da mesma forma que dependências comuns: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 non-Annotated -=== "Python 3.8 non-Annotated" +/// tip | "Dica" - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +Utilize a versão com `Annotated` se possível - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Valores de retorno @@ -108,26 +142,37 @@ E elas também podem ou não retornar valores, eles não serão utilizados. Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | "Dica" - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` -=== "Python 3.8+" - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// -=== "Python 3.8 non-Annotated" + Utilize a versão com `Annotated` se possível - !!! tip "Dica" - Utilize a versão com `Annotated` se possível +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependências para um grupo de *operações de rota* diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 8b4175fc5..16c2cf899 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ O FastAPI possui suporte para dependências que realizam . +/// tip | "Dica" + +Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados usando o prefixo 'X-'. + +Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette. + +/// + +/// note | "Detalhes técnicos" - Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette. +Você também pode usar `from starlette.requests import Request`. -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.requests import Request`. +**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. - **FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ### Antes e depois da `response` diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 13a87240f..c57813780 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -!!! warning "Aviso" - Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. +/// warning | "Aviso" + +Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. + +/// ## Código de Status da Resposta @@ -13,52 +16,67 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette import status`. +/// note | "Detalhes Técnicos" + +Você também poderia usar `from starlette import status`. + +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. +/// ## Tags Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "Python 3.9 and above" +//// tab | Python 3.9 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.10 and above" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -80,23 +98,29 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. Você pode adicionar um `summary` e uma `description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## Descrição do docstring @@ -104,23 +128,29 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// Ela será usada nas documentações interativas: @@ -131,31 +161,43 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | Python 3.9 and above + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.10 and above + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "Python 3.9 and above" +/// info | "Informação" - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. -=== "Python 3.10 and above" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info "Informação" - Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. +OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. -!!! check - OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. +Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". - Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". +/// diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index eb0d31dc3..08ed03f75 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// ## Declare metadados @@ -24,24 +28,31 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -!!! note "Nota" - Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. +//// - Então, você deve declará-lo com `...` para marcá-lo como obrigatório. +/// note | "Nota" - Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. +Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. + +Então, você deve declará-lo com `...` para marcá-lo como obrigatório. + +Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. + +/// ## Ordene os parâmetros de acordo com sua necessidade @@ -121,18 +132,24 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -!!! info "Informação" - `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. +/// info | "Informação" + +`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. + +Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. + +/// + +/// note | "Detalhes Técnicos" - Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. +Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. -!!! note "Detalhes Técnicos" - Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. +Que quando chamadas, retornam instâncias de classes de mesmo nome. - Que quando chamadas, retornam instâncias de classes de mesmo nome. +Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. - Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. +Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. - Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. +Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. - Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. +/// diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index 27aa9dfcf..fb872e4f5 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -24,7 +24,12 @@ Você pode declarar o tipo de um parâmetro na função usando as anotações pa Nesse caso, `item_id` está sendo declarado como um `int`. -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Isso vai dar à você suporte do seu editor dentro das funções, com verificações de erros, autocompletar, etc. ## Conversão de dados @@ -35,7 +40,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing" automático no request . @@ -63,7 +73,12 @@ devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: http://127.0.0.1:8000/items/4.2 -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados. Observe que o erro também mostra claramente o ponto exato onde a validação não passou. @@ -76,7 +91,12 @@ Quando você abrir o seu navegador em -!!! check "Verifique" +/// check | "Verifique" + + + +/// + Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI). Veja que o parâmetro de rota está declarado como sendo um inteiro (int). @@ -131,10 +151,18 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "informação" - Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. +/// info | "informação" + +Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. + +/// + +/// tip | "Dica" + + + +/// -!!! tip "Dica" Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de modelos de Machine Learning (aprendizado de máquina). ### Declare um *parâmetro de rota* @@ -171,7 +199,12 @@ Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_na {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value` #### Retorne *membros de enumeration* @@ -225,7 +258,12 @@ Então, você poderia usar ele com: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`). Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`. diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 9a9e071db..eac879593 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -10,10 +10,13 @@ Vamos utilizar essa aplicação como exemplo: O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | "Observação" - O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. + +/// ## Validação adicional @@ -51,22 +54,25 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -!!! info "Informação" - Tenha em mente que o FastAPI se preocupa com a parte: +/// info | "Informação" - ```Python - = None - ``` +Tenha em mente que o FastAPI se preocupa com a parte: - Ou com: +```Python += None +``` - ```Python - = Query(default=None) - ``` +Ou com: - E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. +```Python += Query(default=None) +``` + +E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. - O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. +O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. + +/// Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos: @@ -112,8 +118,11 @@ Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_leng {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "Observação" - O parâmetro torna-se opcional quando possui um valor padrão. +/// note | "Observação" + +O parâmetro torna-se opcional quando possui um valor padrão. + +/// ## Torne-o obrigatório @@ -141,8 +150,11 @@ Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Q {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "Informação" - Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". +/// info | "Informação" + +Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". + +/// Dessa forma o **FastAPI** saberá que o parâmetro é obrigatório. @@ -175,8 +187,11 @@ Assim, a resposta para essa URL seria: } ``` -!!! tip "Dica" - Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. +/// tip | "Dica" + +Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. + +/// A documentação interativa da API irá atualizar de acordo, permitindo múltiplos valores: @@ -215,10 +230,13 @@ Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "Observação" - Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. +/// note | "Observação" - Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. +Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. + +Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. + +/// ## Declarando mais metadados @@ -226,10 +244,13 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -!!! note "Observação" - Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. +/// note | "Observação" + +Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. + +Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. - Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. +/// Você pode adicionar um `title`: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index ff6f38fe5..78d54f09b 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -63,39 +63,49 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -!!! check "Verificar" - Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// check | "Verificar" + +Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// ## Conversão dos tipos de parâmetros de consulta Você também pode declarar tipos `bool`, e eles serão convertidos: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Nesse caso, se você for para: @@ -137,17 +147,21 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` + +//// ## Parâmetros de consulta obrigatórios @@ -203,17 +217,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// Nesse caso, existem 3 parâmetros de consulta: @@ -221,5 +239,8 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -!!! tip "Dica" - Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. +/// tip | "Dica" + +Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 22954761b..2cf406386 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,11 +2,13 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -!!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +/// info | "Informação" - Por exemplo: `pip install python-multipart`. +Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +Por exemplo: `pip install python-multipart`. + +/// ## Importe `File` e `Form` @@ -26,10 +28,13 @@ Os arquivos e campos de formulário serão carregados como dados de formulário E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. +/// warning | "Aviso" + +Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. - Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 0eb67391b..fc8c7bbad 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,10 +2,13 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -!!! info "Informação" - Para usar formulários, primeiro instale `python-multipart`. +/// info | "Informação" - Ex: `pip install python-multipart`. +Para usar formulários, primeiro instale `python-multipart`. + +Ex: `pip install python-multipart`. + +/// ## Importe `Form` @@ -29,11 +32,17 @@ A spec exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -!!! info "Informação" - `Form` é uma classe que herda diretamente de `Body`. +/// info | "Informação" + +`Form` é uma classe que herda diretamente de `Body`. + +/// + +/// tip | "Dica" -!!! tip "Dica" - Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). +Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// ## Sobre "Campos de formulário" @@ -41,17 +50,23 @@ A forma como os formulários HTML (`
`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -!!! note "Detalhes técnicos" - Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. +/// note | "Detalhes técnicos" + +Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. + + Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. + +/// - Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. +/// warning | "Aviso" - Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. +Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. +Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. - Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2df17d4ea..dc8e12048 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Nota" - Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. +/// note | "Nota" + +Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. + +/// O parâmetro `status_code` recebe um número com o código de status HTTP. -!!! info "Informação" - `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. +/// info | "Informação" + +`status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. + +/// Dessa forma: @@ -27,15 +33,21 @@ Dessa forma: -!!! note "Nota" - Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. +/// note | "Nota" + +Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. + +O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. - O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. +/// ## Sobre os códigos de status HTTP -!!! note "Nota" - Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. +/// note | "Nota" + +Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. + +/// Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta. @@ -55,8 +67,11 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -!!! tip "Dica" - Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. +/// tip | "Dica" + +Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. + +/// ## Atalho para lembrar os nomes @@ -80,11 +95,13 @@ Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa form -!!! note "Detalhes técnicos" - Você também pode usar `from starlette import status`. +/// note | "Detalhes técnicos" + +Você também pode usar `from starlette import status`. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ## Alterando o padrão diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index d04dc1a26..a291db045 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -14,10 +14,13 @@ Você pode declarar um `example` para um modelo Pydantic usando `Config` e `sche Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. -!!! tip "Dica" - Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. +/// tip | "Dica" - Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. +Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. + +Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. + +/// ## `Field` de argumentos adicionais @@ -29,8 +32,11 @@ Você pode usar isso para adicionar um `example` para cada campo: {!../../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "Atenção" - Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. +/// warning | "Atenção" + +Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. + +/// ## `example` e `examples` no OpenAPI @@ -85,10 +91,13 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: ## Detalhes técnicos -!!! warning "Atenção" - Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. +/// warning | "Atenção" + +Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. + +Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. - Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. +/// Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 4331a0bc3..007fefcb9 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -25,7 +25,12 @@ Copie o exemplo em um arquivo `main.py`: ## Execute-o -!!! info "informação" +/// info | "informação" + + + +/// + Primeiro, instale `python-multipart`. Ex: `pip install python-multipart`. @@ -52,7 +57,12 @@ Você verá algo deste tipo: -!!! check "Botão de Autorizar!" +/// check | "Botão de Autorizar!" + + + +/// + Você já tem um novo "botão de autorizar!". E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar. @@ -61,7 +71,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi -!!! note "Nota" +/// note | "Nota" + + + +/// + Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá. Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API. @@ -104,7 +119,12 @@ Então, vamos rever de um ponto de vista simplificado: Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. -!!! info "informação" +/// info | "informação" + + + +/// + Um token "bearer" não é a única opção. Mas é a melhor no nosso caso. @@ -119,7 +139,12 @@ Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passam {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "Dica" +/// tip | "Dica" + + + +/// + Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`. Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`. @@ -130,7 +155,12 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -!!! info "informação" +/// info | "informação" + + + +/// + Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`. Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso. @@ -157,7 +187,12 @@ Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). -!!! info "Detalhes técnicos" +/// info | "Detalhes técnicos" + + + +/// + **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`. Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI. diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index f94a8ab62..2f23aa47e 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -!!! tip "Dica" - Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. +/// tip | "Dica" +Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -!!! tip "Dica" - Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. +/// tip | "Dica" + +Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. + +O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. - O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. +/// ## **FastAPI** utilitários diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 009158fc6..efaf07dfb 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.staticfiles import StaticFiles`. +/// note | "Detalhes técnicos" - O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. +Você também pode usar `from starlette.staticfiles import StaticFiles`. + +O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. + +/// ### O que é "Montagem" diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 24a45fa55..413bf70b2 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,12 +33,18 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -!!! note "Заметка" - Django REST Framework был создан Tom Christie. - Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. +/// note | "Заметка" -!!! check "Идея для **FastAPI**" - Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. +Django REST Framework был создан Tom Christie. +Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. + +/// + +/// check | "Идея для **FastAPI**" + +Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. + +/// ### Flask @@ -56,11 +62,13 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -!!! check "Идеи для **FastAPI**" - Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. +/// check | "Идеи для **FastAPI**" + +Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. - Должна быть простая и лёгкая в использовании система маршрутизации запросов. +Должна быть простая и лёгкая в использовании система маршрутизации запросов. +/// ### Requests @@ -100,11 +108,13 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -!!! check "Идеи для **FastAPI**" - * Должен быть простой и понятный API. - * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. - * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// check | "Идеи для **FastAPI**" + +* Должен быть простой и понятный API. +* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. +* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// ### Swagger / OpenAPI @@ -119,16 +129,19 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -!!! check "Идеи для **FastAPI**" - Использовать открытые стандарты для спецификаций API вместо самодельных схем. +/// check | "Идеи для **FastAPI**" - Совместимость с основанными на стандартах пользовательскими интерфейсами: +Использовать открытые стандарты для спецификаций API вместо самодельных схем. - * Swagger UI - * ReDoc +Совместимость с основанными на стандартах пользовательскими интерфейсами: - Они были выбраны за популярность и стабильность. - Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. +* Swagger UI +* ReDoc + +Они были выбраны за популярность и стабильность. +Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. + +/// ### REST фреймворки для Flask @@ -152,8 +165,11 @@ def read_url(): Итак, чтобы определить каждую схему, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -!!! check "Идея для **FastAPI**" - Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. +/// check | "Идея для **FastAPI**" + +Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. + +/// ### Webargs @@ -165,11 +181,17 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -!!! info "Информация" - Webargs бы создан разработчиками Marshmallow. +/// info | "Информация" + +Webargs бы создан разработчиками Marshmallow. + +/// -!!! check "Идея для **FastAPI**" - Должна быть автоматическая проверка входных данных. +/// check | "Идея для **FastAPI**" + +Должна быть автоматическая проверка входных данных. + +/// ### APISpec @@ -190,11 +212,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -!!! info "Информация" - APISpec тоже был создан авторами Marshmallow. +/// info | "Информация" + +APISpec тоже был создан авторами Marshmallow. + +/// + +/// check | "Идея для **FastAPI**" + +Необходима поддержка открытого стандарта для API - OpenAPI. -!!! check "Идея для **FastAPI**" - Необходима поддержка открытого стандарта для API - OpenAPI. +/// ### Flask-apispec @@ -218,11 +246,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info "Информация" - Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. +/// info | "Информация" -!!! check "Идея для **FastAPI**" - Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. +Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. + +/// + +/// check | "Идея для **FastAPI**" + +Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. + +/// ### NestJSAngular) @@ -242,25 +276,34 @@ Marshmallow и Webargs осуществляют проверку, анализ Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -!!! check "Идеи для **FastAPI** " - Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. +/// check | "Идеи для **FastAPI** " + +Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. + +Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. - Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. +/// ### Sanic Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -!!! note "Технические детали" - В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. +/// note | "Технические детали" - Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. +В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. -!!! check "Идеи для **FastAPI**" - Должна быть сумасшедшая производительность. +Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. - Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). +/// + +/// check | "Идеи для **FastAPI**" + +Должна быть сумасшедшая производительность. + +Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). + +/// ### Falcon @@ -275,12 +318,15 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -!!! check "Идея для **FastAPI**" - Найдите способы добиться отличной производительности. +/// check | "Идея для **FastAPI**" + +Найдите способы добиться отличной производительности. + +Объявлять параметры `ответа сервера` в функциях, как в Hug. - Объявлять параметры `ответа сервера` в функциях, как в Hug. +Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. - Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. +/// ### Molten @@ -302,11 +348,14 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -!!! check "Идея для **FastAPI**" - Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". - Это улучшает помощь редактора и раньше это не было доступно в Pydantic. +/// check | "Идея для **FastAPI**" - Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). +Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". +Это улучшает помощь редактора и раньше это не было доступно в Pydantic. + +Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). + +/// ### Hug @@ -325,15 +374,21 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -!!! info "Информация" - Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. +/// info | "Информация" + +Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. + +/// + +/// check | "Идеи для **FastAPI**" + +Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. -!!! check "Идеи для **FastAPI**" - Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. +Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. - Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. +Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. - Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. +/// ### APIStar (<= 0.5) @@ -363,24 +418,30 @@ Hug был одним из первых фреймворков, реализов Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -!!! info "Информация" - APIStar был создан Tom Christie. Тот самый парень, который создал: +/// info | "Информация" - * Django REST Framework - * Starlette (на котором основан **FastAPI**) - * Uvicorn (используемый в Starlette и **FastAPI**) +APIStar был создан Tom Christie. Тот самый парень, который создал: -!!! check "Идеи для **FastAPI**" - Воплощение. +* Django REST Framework +* Starlette (на котором основан **FastAPI**) +* Uvicorn (используемый в Starlette и **FastAPI**) - Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. +/// - После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. +/// check | "Идеи для **FastAPI**" - Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. - Это была последняя капля, сподвигнувшая на создание **FastAPI**. +Воплощение. - Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. +Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. + +После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. + +Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. +Это была последняя капля, сподвигнувшая на создание **FastAPI**. + +Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. + +/// ## Что используется в **FastAPI** @@ -391,10 +452,13 @@ Pydantic - это библиотека для валидации данных, Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -!!! check "**FastAPI** использует Pydantic" - Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). +/// check | "**FastAPI** использует Pydantic" + +Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). + +Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. - Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. +/// ### Starlette @@ -424,19 +488,25 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -!!! note "Технические детали" - ASGI - это новый "стандарт" разработанный участниками команды Django. - Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. +/// note | "Технические детали" - Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. - Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. +ASGI - это новый "стандарт" разработанный участниками команды Django. +Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. -!!! check "**FastAPI** использует Starlette" - В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. +Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. +Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. - Класс `FastAPI` наследуется напрямую от класса `Starlette`. +/// - Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. +/// check | "**FastAPI** использует Starlette" + +В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. + +Класс `FastAPI` наследуется напрямую от класса `Starlette`. + +Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. + +/// ### Uvicorn @@ -448,12 +518,15 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -!!! check "**FastAPI** рекомендует его" - Как основной сервер для запуска приложения **FastAPI**. +/// check | "**FastAPI** рекомендует его" + +Как основной сервер для запуска приложения **FastAPI**. + +Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. - Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. +Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. - Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. +/// ## Тестовые замеры и скорость diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 20dbb108b..6c5d982df 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - `await` можно использовать только внутри функций, объявленных с использованием `async def`. +/// note + +`await` можно использовать только внутри функций, объявленных с использованием `async def`. + +/// --- @@ -444,14 +447,17 @@ Starlette (и **FastAPI**) основаны на +
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` + +
- +//// -=== "Windows PowerShell" +//// tab | Windows PowerShell + +
+ +```console +$ .\env\Scripts\Activate.ps1 +``` -
+
- ```console - $ .\env\Scripts\Activate.ps1 - ``` +//// -
+//// tab | Windows Bash -=== "Windows Bash" +Если Вы пользуетесь Bash для Windows (например:
Git Bash): - Если Вы пользуетесь Bash для Windows (например: Git Bash): +
-
+```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// Проверьте, что всё сработало: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which pip -
+some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +
- some/directory/fastapi/env/bin/pip - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +
-
+//// Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip "Подсказка" - Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. +/// tip | "Подсказка" + +Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. + +Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. +/// ### pip @@ -149,9 +162,11 @@ $ bash scripts/format.sh Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. -!!! tip "Подсказка" +/// tip | "Подсказка" - Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. +Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. + +/// Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. @@ -239,10 +254,13 @@ $ uvicorn tutorial001:app --reload * Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. -!!! tip "Подсказка" - Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. +/// tip | "Подсказка" + +Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. + +Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. - Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. +/// * Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. @@ -264,8 +282,11 @@ $ uvicorn tutorial001:app --reload Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. -!!! tip "Подсказка" - Главный ("официальный") язык - английский, директория для него `docs/en/`. +/// tip | "Подсказка" + +Главный ("официальный") язык - английский, директория для него `docs/en/`. + +/// Вы можете запустить сервер документации на испанском: @@ -304,8 +325,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Подсказка" - Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. +/// tip | "Подсказка" + +Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. + +/// * Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: @@ -376,10 +400,13 @@ Updating en После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. -!!! tip "Подсказка" - Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. +/// tip | "Подсказка" + +Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. + +Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 +/// Начните перевод с главной страницы `docs/ht/index.md`. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 26db356c1..c41025790 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -151,10 +151,13 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -!!! tip "Заметка" - ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. +/// tip | "Заметка" - Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. +... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. + +Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. + +/// Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе. @@ -238,10 +241,13 @@ * **Облачные сервисы**, которые позаботятся обо всём за Вас * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. -!!! tip "Заметка" - Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. +/// tip | "Заметка" + +Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. + +Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. - Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. +/// ## Шаги, предшествующие запуску @@ -257,10 +263,13 @@ Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -!!! tip "Заметка" - Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. +/// tip | "Заметка" - Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 +Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. + +Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 + +/// ### Примеры стратегий запуска предварительных шагов @@ -272,8 +281,11 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -!!! tip "Заметка" - Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. +/// tip | "Заметка" + +Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. + +/// ## Утилизация ресурсов diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index ce4972c4f..e627d01fe 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,8 +4,11 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -!!! tip "Подсказка" - Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) +/// tip | "Подсказка" + +Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) + +///
Развернуть Dockerfile 👀 @@ -132,10 +135,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info "Информация" - Существуют и другие инструменты управления зависимостями. +/// info | "Информация" + +Существуют и другие инструменты управления зависимостями. - В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 +В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 + +/// ### Создать приложение **FastAPI** @@ -222,8 +228,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 +/// tip | "Подсказка" + +Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 + +/// На данном этапе структура проекта должны выглядеть так: @@ -294,10 +303,13 @@ $ docker build -t myimage . -!!! tip "Подсказка" - Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. +/// tip | "Подсказка" + +Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. + +В данном случае это та же самая директория (`.`). - В данном случае это та же самая директория (`.`). +/// ### Запуск Docker-контейнера @@ -395,8 +407,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -!!! tip "Подсказка" - Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. +/// tip | "Подсказка" + +Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. + +/// В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу. @@ -424,8 +439,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -!!! tip "Подсказка" - **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. +/// tip | "Подсказка" + +**Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. + +/// Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). @@ -504,8 +522,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -!!! info "Информация" - При использовании Kubernetes, это может быть Инициализирующий контейнер. +/// info | "Информация" + +При использовании Kubernetes, это может быть Инициализирующий контейнер. + +/// При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. @@ -521,8 +542,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "Предупреждение" - Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). +/// warning | "Предупреждение" + +Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + +/// В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. @@ -530,8 +554,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. -!!! tip "Подсказка" - Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | "Подсказка" + +Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Количество процессов в официальном Docker-образе @@ -659,8 +686,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. +/// tip | "Подсказка" + +Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. + +/// **Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index 5aa300331..3d487c465 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -4,8 +4,11 @@ Но всё несколько сложнее. -!!! tip "Заметка" - Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. +/// tip | "Заметка" + +Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. + +/// Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке https://howhttps.works/. @@ -75,8 +78,11 @@ Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -!!! tip "Заметка" - Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. +/// tip | "Заметка" + +Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. + +/// ### DNS @@ -122,8 +128,11 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -!!! tip "Заметка" - Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. +/// tip | "Заметка" + +Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. + +/// ### HTTPS-запрос diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 0b24c0695..78363cef8 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -25,76 +25,89 @@ Вы можете установить сервер, совместимый с протоколом ASGI, так: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. +* Uvicorn, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
+ +/// tip | "Подсказка" - !!! tip "Подсказка" - С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. +С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. - В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. +В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. -=== "Hypercorn" +/// - * Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. +//// -
+//// tab | Hypercorn - ```console - $ pip install hypercorn +* Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. - ---> 100% - ``` +
-
+```console +$ pip install hypercorn + +---> 100% +``` + +
- ...или какой-либо другой ASGI сервер. +...или какой-либо другой ASGI сервер. + +//// ## Запуск серверной программы Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
-=== "Hypercorn" +```console +$ hypercorn main:app --bind 0.0.0.0:80 -
+Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +
- Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +//// -
+/// warning | "Предупреждение" -!!! warning "Предупреждение" +Не забудьте удалить опцию `--reload`, если ранее пользовались ею. - Не забудьте удалить опцию `--reload`, если ранее пользовались ею. +Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. - Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. +Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. - Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. +/// ## Hypercorn с Trio diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index f410e3936..17b6446d9 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -!!! tip "Подсказка" - "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. +/// tip | "Подсказка" + +"ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. + +/// Итак, вы можете закрепить версию следующим образом: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -!!! tip "Подсказка" - "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. +/// tip | "Подсказка" + +"МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. + +/// ## Обновление версий FastAPI diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md index 0a4cda27b..2c0e153e2 100644 --- a/docs/ru/docs/external-links.md +++ b/docs/ru/docs/external-links.md @@ -6,8 +6,11 @@ Вот неполный список некоторых из них. -!!! tip - Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. +/// tip + +Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index baa4ec778..31f245e7a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,10 +66,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "Информация" - `**second_user_data` означает: +/// info | "Информация" - Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . +`**second_user_data` означает: + +Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . + +/// ### Поддержка редакторов (IDE) diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index b007437bc..fa8200817 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -162,12 +162,15 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -!!! info "Информация" - К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. +/// info | "Информация" - Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 +К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. - Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 +Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 + +Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 + +/// * Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах. @@ -218,10 +221,13 @@ Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI. -!!! tip "Подсказка" - Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. +/// tip | "Подсказка" + +Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. + +Используйте этот чат только для бесед на отвлечённые темы. - Используйте этот чат только для бесед на отвлечённые темы. +/// ### Не использовать чаты для вопросов diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 3c8492c67..c052bc675 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -12,8 +12,11 @@ Python имеет поддержку необязательных аннотац Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них. -!!! note - Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. +/// note + +Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. + +/// ## Мотивация @@ -172,10 +175,13 @@ John Doe {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip - Эти внутренние типы в квадратных скобках называются «параметрами типов». +/// tip + +Эти внутренние типы в квадратных скобках называются «параметрами типов». + +В этом случае `str` является параметром типа, передаваемым в `List`. - В этом случае `str` является параметром типа, передаваемым в `List`. +/// Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`". @@ -281,8 +287,11 @@ John Doe {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Чтобы узнать больше о Pydantic, читайте его документацию. +/// info + +Чтобы узнать больше о Pydantic, читайте его документацию. + +/// **FastAPI** целиком основан на Pydantic. @@ -310,5 +319,8 @@ John Doe Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы. -!!! info - Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. +/// info + +Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. + +/// diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 73ba860bc..073276848 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -57,17 +57,21 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 02a598004..f4db0e9ff 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ Сначала вы должны импортировать его: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | Python 3.8+ -!!! warning "Внимание" - Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "Внимание" + +Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). + +/// ## Объявление атрибутов модели Вы можете использовать функцию `Field` с атрибутами модели: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -!!! note "Технические детали" - На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. +/// note | "Технические детали" - И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. +На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. - У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. +И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. - Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. -!!! tip "Подсказка" - Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. +Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. + +/// + +/// tip | "Подсказка" + +Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. + +/// ## Добавление дополнительной информации @@ -58,9 +75,12 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -!!! warning "Внимание" - Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. - Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. +/// warning | "Внимание" + +Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. +Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. + +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index ffba1d0f4..107e6293b 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip | "Заметка" + +Рекомендуется использовать `Annotated` версию, если это возможно. + +/// + +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip | "Заметка" -!!! note "Заметка" - Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note | "Заметка" + +Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. + +/// ## Несколько параметров тела запроса @@ -62,17 +81,21 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -93,9 +116,11 @@ } ``` -!!! note "Внимание" - Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// note | "Внимание" + +Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// **FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`. @@ -111,41 +136,57 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// tip | "Заметка" -=== "Python 3.8+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Заметка" - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +/// + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +//// В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -185,44 +226,63 @@ q: str | None = None Например: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "Заметка" + +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +/// tip | "Заметка" -=== "Python 3.10+ non-Annotated" +Рекомендуется использовать `Annotated` версию, если это возможно. - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// info | "Информация" - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. -!!! info "Информация" - `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. +/// ## Добавление одного body-параметра @@ -238,41 +298,57 @@ item: Item = Body(embed=True) так же, как в этом примере: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip | "Заметка" -=== "Python 3.9+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +/// tip | "Заметка" - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Рекомендуется использовать `Annotated` версию, если это возможно. -=== "Python 3.8+ non-Annotated" +/// - !!! tip "Заметка" - Рекомендуется использовать `Annotated` версию, если это возможно. +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 51a32ba56..ecb8b92a7 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -61,23 +65,29 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Типы множеств @@ -87,23 +97,29 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -125,45 +141,57 @@ my_list: List[str] Например, мы можем определить модель `Image`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -196,23 +224,29 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -220,23 +254,29 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info "Информация" - Заметьте, что теперь у ключа `images` есть список объектов изображений. +/// info | "Информация" + +Заметьте, что теперь у ключа `images` есть список объектов изображений. + +/// ## Глубоко вложенные модели Вы можете определять модели с произвольным уровнем вложенности: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info | "Информация" - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` -!!! info "Информация" - Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` +/// ## Тела с чистыми списками элементов @@ -308,17 +360,21 @@ images: list[Image] например так: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Универсальная поддержка редактора @@ -348,26 +404,33 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip | "Совет" - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Имейте в виду, что JSON поддерживает только ключи типа `str`. -!!! tip "Совет" - Имейте в виду, что JSON поддерживает только ключи типа `str`. +Но Pydantic обеспечивает автоматическое преобразование данных. - Но Pydantic обеспечивает автоматическое преобразование данных. +Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. - Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. +А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. - А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index 4998ab31a..c458329d8 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -48,14 +54,17 @@ Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. -!!! note "Технические детали" - `PATCH` менее распространен и известен, чем `PUT`. +/// note | "Технические детали" + +`PATCH` менее распространен и известен, чем `PUT`. + +А многие команды используют только `PUT`, даже для частичного обновления. - А многие команды используют только `PUT`, даже для частичного обновления. +Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. - Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. +Но в данном руководстве более или менее понятно, как они должны использоваться. - Но в данном руководстве более или менее понятно, как они должны использоваться. +/// ### Использование параметра `exclude_unset` в Pydantic @@ -65,23 +74,29 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Использование параметра `update` в Pydantic @@ -89,23 +104,29 @@ Например, `stored_item_model.copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Кратко о частичном обновлении @@ -122,32 +143,44 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +Эту же технику можно использовать и для операции HTTP `PUT`. -=== "Python 3.6+" +Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip "Подсказка" - Эту же технику можно использовать и для операции HTTP `PUT`. +/// note | "Технические детали" - Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. +Обратите внимание, что входная модель по-прежнему валидируется. -!!! note "Технические детали" - Обратите внимание, что входная модель по-прежнему валидируется. +Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). - Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). +Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. - Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 5d0e033fd..c3e6326da 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -8,12 +8,15 @@ Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. -!!! info "Информация" - Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. +/// info | "Информация" - Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. +Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. - Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. +Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. + +Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. + +/// ## Импортирование `BaseModel` из Pydantic @@ -110,16 +113,19 @@ -!!! tip "Подсказка" - Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. +/// tip | "Подсказка" + +Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. - Он улучшает поддержку редактором моделей Pydantic в части: +Он улучшает поддержку редактором моделей Pydantic в части: - * автодополнения, - * проверки типов, - * рефакторинга, - * поиска, - * инспектирования. +* автодополнения, +* проверки типов, +* рефакторинга, +* поиска, +* инспектирования. + +/// ## Использование модели @@ -155,10 +161,13 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -!!! note "Заметка" - FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. +/// note | "Заметка" + +FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. + +Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. - Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. +/// ## Без Pydantic diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 5f99458b6..e88b9d7ee 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ Сначала импортируйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Cookie` @@ -24,25 +28,35 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | "Технические детали" - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. -=== "Python 3.8+" +Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Технические детали" - `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. +/// info | "Дополнительная информация" - Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. -!!! info "Дополнительная информация" - Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8c7fbc046..852833208 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -78,7 +78,10 @@ Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla. -!!! note "Технические детали" - Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. +/// note | "Технические детали" - **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. +Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. + +/// diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 5fc6a2c1f..685fb7356 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -74,8 +74,11 @@ from myapp import app не будет выполнена. -!!! info "Информация" - Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. +/// info | "Информация" + +Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. + +/// ## Запуск вашего кода с помощью отладчика diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index b6ad25daf..d0471baca 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.10+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -101,117 +117,165 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.6+" +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="12-16" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` + +//// Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.6+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -227,41 +291,57 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -269,20 +349,27 @@ fluffy = Cat(name="Mr Fluffy") Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Последний параметр `CommonQueryParams`, в: @@ -298,77 +385,107 @@ fluffy = Cat(name="Mr Fluffy") В этом случае первый `CommonQueryParams`, в: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). На самом деле можно написать просто: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python - commons = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ...как тут: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -378,101 +495,141 @@ fluffy = Cat(name="Mr Fluffy") Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. Вместо того чтобы писать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...следует написать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.6 без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6 без Annotated - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. Аналогичный пример будет выглядеть следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ...и **FastAPI** будет знать, что делать. -!!! tip "Подсказка" - Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. +/// tip | "Подсказка" + +Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + +Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. - Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. +/// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 2bd096189..11df4b474 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ Это должен быть `list` состоящий из `Depends()`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 без Annotated" +```Python hl_lines="18" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. -!!! Подсказка - Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. +/// подсказка + +Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. - Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. +Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. - Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. +Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. -!!! Дополнительная информация - В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. +/// - Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. +/// дополнительная | информация + +В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. + +Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. + +/// ## Исключения в dependencies и возвращаемые значения @@ -57,51 +72,69 @@ Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 без Annotated -=== "Python 3.8 без Annotated" +/// подсказка - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +Рекомендуется использовать версию с Annotated, если возможно. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Вызов исключений Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 без Annotated - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// подсказка -=== "Python 3.8 без Annotated" +Рекомендуется использовать версию с Annotated, если возможно. - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### Возвращаемые значения @@ -109,26 +142,35 @@ Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 без Annotated -=== "Python 3.8+" +/// подсказка - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +Рекомендуется использовать версию с Annotated, если возможно. -=== "Python 3.8 без Annotated" +/// - !!! Подсказка - Рекомендуется использовать версию с Annotated, если возможно. +```Python hl_lines="9 14" +{!> ../../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## Dependencies для группы *операций путей* diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index cd524cf66..ece7ef8e3 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI поддерживает зависимости, которые выпо Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. -!!! tip "Подсказка" - Обязательно используйте `yield` один-единственный раз. +/// tip | "Подсказка" -!!! note "Технические детали" - Любая функция, с которой может работать: +Обязательно используйте `yield` один-единственный раз. - * `@contextlib.contextmanager` или - * `@contextlib.asynccontextmanager` +/// - будет корректно использоваться в качестве **FastAPI**-зависимости. +/// note | "Технические детали" - На самом деле, FastAPI использует эту пару декораторов "под капотом". +Любая функция, с которой может работать: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` + +будет корректно использоваться в качестве **FastAPI**-зависимости. + +На самом деле, FastAPI использует эту пару декораторов "под капотом". + +/// ## Зависимость базы данных с помощью `yield` @@ -39,10 +45,13 @@ FastAPI поддерживает зависимости, которые выпо {!../../../docs_src/dependencies/tutorial007.py!} ``` -!!! tip "Подсказка" - Можно использовать как `async` так и обычные функции. +/// tip | "Подсказка" + +Можно использовать как `async` так и обычные функции. - **FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. +**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. + +/// ## Зависимость с `yield` и `try` одновременно @@ -66,26 +75,35 @@ FastAPI поддерживает зависимости, которые выпо Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 14 22" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="5 13 21" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="4 12 20" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// И все они могут использовать `yield`. @@ -93,26 +111,35 @@ FastAPI поддерживает зависимости, которые выпо И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +```Python hl_lines="18-19 26-27" +{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="17-18 25-26" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +/// + +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. @@ -122,8 +149,11 @@ FastAPI поддерживает зависимости, которые выпо **FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. -!!! note "Технические детали" - Это работает благодаря Контекстным менеджерам в Python. +/// note | "Технические детали" + +Это работает благодаря Контекстным менеджерам в Python. + +/// **FastAPI** использует их "под капотом" с этой целью. @@ -147,8 +177,11 @@ FastAPI поддерживает зависимости, которые выпо Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -!!! tip "Подсказка" - Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. +/// tip | "Подсказка" + +Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. + +/// Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код. @@ -192,22 +225,31 @@ participant tasks as Background tasks end ``` -!!! info "Дополнительная информация" - Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. +/// info | "Дополнительная информация" + +Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. + +После отправки одного из этих ответов никакой другой ответ не может быть отправлен. - После отправки одного из этих ответов никакой другой ответ не может быть отправлен. +/// -!!! tip "Подсказка" - На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +/// tip | "Подсказка" - Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. +На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. + +/// ## Зависимости с `yield`, `HTTPException` и фоновыми задачами -!!! warning "Внимание" - Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. +/// warning | "Внимание" + +Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. - Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. +Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. + +/// До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен. @@ -215,10 +257,12 @@ participant tasks as Background tasks Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. -!!! tip "Подсказка" +/// tip | "Подсказка" + +Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). +Таким образом, вы, вероятно, получите более чистый код. - Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). - Таким образом, вы, вероятно, получите более чистый код. +/// Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`. @@ -246,10 +290,13 @@ with open("./somefile.txt") as f: ### Использование менеджеров контекста в зависимостях с помощью `yield` -!!! warning "Внимание" - Это более или менее "продвинутая" идея. +/// warning | "Внимание" - Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. +Это более или менее "продвинутая" идея. + +Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. + +/// В Python для создания менеджеров контекста можно создать класс с двумя методами: `__enter__()` и `__exit__()`. @@ -260,16 +307,19 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "Подсказка" - Другой способ создания контекстного менеджера - с помощью: +/// tip | "Подсказка" + +Другой способ создания контекстного менеджера - с помощью: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` или - * `@contextlib.asynccontextmanager` +используйте их для оформления функции с одним `yield`. - используйте их для оформления функции с одним `yield`. +Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. - Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. +Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). - Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). +FastAPI сделает это за вас на внутреннем уровне. - FastAPI сделает это за вас на внутреннем уровне. +/// diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index eb1b4d7c1..9e03e3723 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать 'Annotated' версию, если это возможно. + +/// + +```Python hl_lines="15" +{!> ../../../docs_src/dependencies/tutorial012.py!} +``` + +//// Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index 9fce46b97..b244b3fdc 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,42 +29,57 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="9-12" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Подсказка" +/// tip | "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +/// + +```Python hl_lines="8-11" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` + +//// **И всё.** @@ -84,91 +99,125 @@ И в конце она возвращает `dict`, содержащий эти значения. -!!! info "Информация" +/// info | "Информация" + +**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. - **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. - Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. +Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. - Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. +/// ### Import `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="1" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="13 18" +{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="16 21" +{!> ../../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="11 16" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="15 20" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -176,8 +225,11 @@ И потом функция берёт параметры так же, как *функция обработки пути*. -!!! tip "Подсказка" - В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. +/// tip | "Подсказка" + +В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +/// Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: @@ -198,10 +250,13 @@ common_parameters --> read_users Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. -!!! check "Проверка" - Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. +/// check | "Проверка" + +Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + +Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. - Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. +/// ## Объединяем с `Annotated` зависимостями @@ -215,29 +270,37 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="12 16 21" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="14 18 23" +{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +//// -!!! tip "Подсказка" - Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. +//// tab | Python 3.8+ - Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 +```Python hl_lines="15 19 24" +{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +``` +//// + +/// tip | "Подсказка" + +Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + +Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + +/// Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. @@ -253,8 +316,11 @@ commons: Annotated[dict, Depends(common_parameters)] Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 -!!! note "Информация" - Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. +/// note | "Информация" + +Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +/// ## Интеграция с OpenAPI diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 31f9f43c6..332470396 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -10,41 +10,57 @@ Можно создать первую зависимость следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +//// + +//// tab | Python 3.6+ + +```Python hl_lines="9-10" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` -=== "Python 3.6+" +//// + +//// tab | Python 3.10 без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="6-7" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="9-10" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="8-9" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. @@ -54,41 +70,57 @@ Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="14" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 без Annotated - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.9+" +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.6+" +```Python hl_lines="11" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="13" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +//// Остановимся на объявленных параметрах: @@ -101,46 +133,65 @@ Затем мы можем использовать зависимость вместе с: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="24" +{!> ../../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10 без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="23" - {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+" +/// - ```Python hl_lines="24" - {!> ../../../docs_src/dependencies/tutorial005_an.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "Python 3.10 без Annotated" +//// tab | Python 3.6 без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6 без Annotated" +/// + +```Python hl_lines="22" +{!> ../../../docs_src/dependencies/tutorial005.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +/// info | "Дополнительная информация" -!!! info "Дополнительная информация" - Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. +Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. - Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. +Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. + +/// ```mermaid graph TB @@ -161,22 +212,29 @@ query_extractor --> query_or_cookie_extractor --> read_query В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` - ```Python hl_lines="1" - async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): - return {"fresh_value": fresh_value} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="1" - async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): - return {"fresh_value": fresh_value} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// ## Резюме @@ -186,9 +244,12 @@ query_extractor --> query_or_cookie_extractor --> read_query Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. -!!! tip "Подсказка" - Все это может показаться не столь полезным на этих простых примерах. +/// tip | "Подсказка" + +Все это может показаться не столь полезным на этих простых примерах. + +Но вы увидите как это пригодится в главах посвященных безопасности. - Но вы увидите как это пригодится в главах посвященных безопасности. +И вы также увидите, сколько кода это вам сэкономит. - И вы также увидите, сколько кода это вам сэкономит. +/// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index c26b2c941..02c3587f3 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. @@ -38,5 +42,8 @@ Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. -!!! note "Технические детали" - `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. +/// note | "Технические детали" + +`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. + +/// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index d4727e2d4..2650bb0af 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "Python 3.10 и выше" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 и выше + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | Python 3.10 и выше -=== "Python 3.10 и выше" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 78855313d..2aac76aa3 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -!!! danger "Внимание" - Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. +/// danger | "Внимание" - Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. + +Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Множественные модели Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` + +//// ### Про `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning "Предупреждение" - Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. +/// warning | "Предупреждение" + +Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. + +/// ## Сократите дублирование @@ -158,17 +168,21 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` или `anyOf` @@ -178,20 +192,27 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: -!!! note "Примечание" - При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. +/// note | "Примечание" + +При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. -=== "Python 3.10+" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.8+" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` в Python 3.10 @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## Ответ с произвольным `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index 8a0876bb4..e60d58823 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "Технические детали" - Команда `uvicorn main:app` обращается к: +/// note | "Технические детали" - * `main`: файл `main.py` (модуль Python). - * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. - * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. +Команда `uvicorn main:app` обращается к: + +* `main`: файл `main.py` (модуль Python). +* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. +* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. + +/// В окне вывода появится следующая строка: @@ -136,10 +139,13 @@ OpenAPI описывает схему API. Эта схема содержит о `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -!!! note "Технические детали" - `FastAPI` это класс, который наследуется непосредственно от `Starlette`. +/// note | "Технические детали" + +`FastAPI` это класс, который наследуется непосредственно от `Starlette`. - Вы можете использовать всю функциональность Starlette в `FastAPI`. +Вы можете использовать всю функциональность Starlette в `FastAPI`. + +/// ### Шаг 2: создайте экземпляр `FastAPI` @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Дополнительная иформация" - Термин "path" также часто называется "endpoint" или "route". +/// info | "Дополнительная иформация" + +Термин "path" также часто называется "endpoint" или "route". + +/// При создании API, "путь" является основным способом разделения "задач" и "ресурсов". @@ -250,16 +259,19 @@ https://example.com/items/foo * путь `/` * использующих get операцию -!!! info "`@decorator` Дополнительная информация" - Синтаксис `@something` в Python называется "декоратор". +/// info | "`@decorator` Дополнительная информация" - Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). +Синтаксис `@something` в Python называется "декоратор". - "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. +Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). - В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. +"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. - Это и есть "**декоратор операции пути**". +В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. + +Это и есть "**декоратор операции пути**". + +/// Можно также использовать операции: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Подсказка" - Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. +/// tip | "Подсказка" + +Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. - **FastAPI** не навязывает определенного значения для каждого метода. +**FastAPI** не навязывает определенного значения для каждого метода. - Информация здесь представлена как рекомендация, а не требование. +Информация здесь представлена как рекомендация, а не требование. - Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. +Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. + +/// ### Шаг 4: определите **функцию операции пути** @@ -309,8 +324,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Технические детали" - Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. +/// note | "Технические детали" + +Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. + +/// ### Шаг 5: верните результат diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index 40b6f9bc4..028f3e0d2 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -63,12 +63,15 @@ } ``` -!!! tip "Подсказка" - При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. +/// tip | "Подсказка" - Вы можете передать `dict`, `list` и т.д. +При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. - Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. +Вы можете передать `dict`, `list` и т.д. + +Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. + +/// ## Добавление пользовательских заголовков @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Технические детали" - Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. +/// note | "Технические детали" + +Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. +/// ## Переопределение стандартных обработчиков исключений @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` или `ValidationError` -!!! warning "Внимание" - Это технические детали, которые можно пропустить, если они не важны для вас сейчас. +/// warning | "Внимание" + +Это технические детали, которые можно пропустить, если они не важны для вас сейчас. + +/// `RequestValidationError` является подклассом Pydantic `ValidationError`. @@ -183,10 +192,13 @@ path -> item_id {!../../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Технические детали" - Можно также использовать `from starlette.responses import PlainTextResponse`. +/// note | "Технические детали" + +Можно также использовать `from starlette.responses import PlainTextResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Используйте тело `RequestValidationError` diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 1be4ac707..3b5e38328 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ Сперва импортируйте `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Header` @@ -48,49 +64,71 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! note "Технические детали" - `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. +/// - Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info "Дополнительная информация" - Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. +//// + +/// note | "Технические детали" + +`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. + +Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +/// + +/// info | "Дополнительная информация" + +Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. + +/// ## Автоматическое преобразование @@ -108,44 +146,63 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! warning "Внимание" - Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// warning | "Внимание" + +Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. + +/// ## Повторяющиеся заголовки @@ -157,50 +214,71 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ без Annotated" +//// tab | Python 3.9+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index ea3a1c37a..4cf45c0ed 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -!!! note "Технические детали" - Вы также можете установить его по частям. +/// note | "Технические детали" - Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: +Вы также можете установить его по частям. - ``` - pip install fastapi - ``` +Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: - Также установите `uvicorn` для работы в качестве сервера: +``` +pip install fastapi +``` + +Также установите `uvicorn` для работы в качестве сервера: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. - И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. +/// ## Продвинутое руководство пользователя diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 0c6940d0e..9799fe538 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -21,8 +21,11 @@ {!../../../docs_src/metadata/tutorial001.py!} ``` -!!! tip "Подсказка" - Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. +/// tip | "Подсказка" + +Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. + +/// С этой конфигурацией автоматическая документация API будут выглядеть так: @@ -54,8 +57,11 @@ Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -!!! tip "Подсказка" - Вам необязательно добавлять метаданные для всех используемых тегов +/// tip | "Подсказка" + +Вам необязательно добавлять метаданные для всех используемых тегов + +/// ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: @@ -64,8 +70,11 @@ {!../../../docs_src/metadata/tutorial004.py!} ``` -!!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. +/// info | "Дополнительная информация" + +Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### Проверьте документацию diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index db99409f4..26b1726ad 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -!!! warning "Внимание" - Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. +/// warning | "Внимание" + +Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. + +/// ## Коды состояния @@ -13,52 +16,67 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. -!!! note "Технические детали" - Вы также можете использовать `from starlette import status`. +/// note | "Технические детали" + +Вы также можете использовать `from starlette import status`. + +**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. - **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. +/// ## Теги Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -80,23 +98,29 @@ Вы можете добавить параметры `summary` и `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Описание из строк документации @@ -104,23 +128,29 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// Он будет использован в интерактивной документации: @@ -130,31 +160,43 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info | "Дополнительная информация" - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check | "Технические детали" -!!! info "Дополнительная информация" - Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. +OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. -!!! check "Технические детали" - OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. +Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". - Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". +/// diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index 0baf51fa9..ced12c826 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// info | "Информация" - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). -!!! info "Информация" - Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). +Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. - Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. +Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. - Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. +/// ## Определите метаданные @@ -55,53 +74,75 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! note "Примечание" - Path-параметр всегда является обязательным, поскольку он составляет часть пути. +/// - Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note | "Примечание" + +Path-параметр всегда является обязательным, поскольку он составляет часть пути. + +Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. + +Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. + +/// ## Задайте нужный вам порядок параметров -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | "Подсказка" + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`. @@ -117,33 +158,45 @@ Поэтому вы можете определить функцию так: -=== "Python 3.8 без Annotated" +//// tab | Python 3.8 без Annotated + +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Задайте нужный вам порядок параметров, полезные приёмы -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | "Подсказка" + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится. @@ -168,17 +221,21 @@ Python не будет ничего делать с `*`, но он будет з Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Валидация числовых данных: больше или равно @@ -186,26 +243,35 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Валидация числовых данных: больше и меньше или равно @@ -214,26 +280,35 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -245,26 +320,35 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для lt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Резюме @@ -277,16 +361,22 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -!!! info "Информация" - `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. +/// info | "Информация" + +`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. + +Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. + +/// + +/// note | "Технические детали" - Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. +`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. -!!! note "Технические детали" - `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. +Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. - Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. +Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. - Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. +Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. - Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. +/// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 1241e0919..dc3d64af4 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Здесь, `item_id` объявлен типом `int`. -!!! check "Заметка" - Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). +/// check | "Заметка" + +Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). + +/// ## Преобразование данных @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "Заметка" - Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. +/// check | "Заметка" + +Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. + +Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. - Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. +/// ## Проверка данных @@ -63,12 +69,15 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2 -!!! check "Заметка" - **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. +/// check | "Заметка" - Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. +**FastAPI** обеспечивает проверку типов, используя всё те же определения типов. - Это очень полезно при разработке и отладке кода, который взаимодействует с API. +Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. + +Это очень полезно при разработке и отладке кода, который взаимодействует с API. + +/// ## Документация @@ -76,10 +85,13 @@ -!!! check "Заметка" - Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). +/// check | "Заметка" + +Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). + +Обратите внимание, что параметр пути объявлен целочисленным. - Обратите внимание, что параметр пути объявлен целочисленным. +/// ## Преимущества стандартизации, альтернативная документация @@ -140,11 +152,17 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Дополнительная информация" - Перечисления (enum) доступны в Python начиная с версии 3.4. +/// info | "Дополнительная информация" -!!! tip "Подсказка" - Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. +Перечисления (enum) доступны в Python начиная с версии 3.4. + +/// + +/// tip | "Подсказка" + +Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. + +/// ### Определение *параметра пути* @@ -180,8 +198,11 @@ {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Подсказка" - Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. +/// tip | "Подсказка" + +Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. + +/// #### Возврат *элементов перечисления* @@ -233,10 +254,13 @@ OpenAPI не поддерживает способов объявления *п {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Подсказка" - Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). +/// tip | "Подсказка" + +Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). + +В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. - В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. +/// ## Резюме Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете: diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 108aefefc..e6653a837 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Давайте рассмотрим следующий пример: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. -!!! note "Технические детали" - FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. +/// note | "Технические детали" - `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. +FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. + +`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. + +/// ## Расширенная валидация @@ -34,23 +41,27 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N * `Query` из пакета `fastapi`: * `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. + +```Python hl_lines="1 3" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` - В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. - В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. +Эта библиотека будет установлена вместе с FastAPI. - Эта библиотека будет установлена вместе с FastAPI. +```Python hl_lines="3-4" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// ## `Annotated` как тип для query-параметра `q` @@ -60,31 +71,39 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N У нас была аннотация следующего типа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: str | None = None - ``` +```Python +q: str | None = None +``` -=== "Python 3.8+" +//// - ```Python - q: Union[str, None] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// Вот что мы получим, если обернём это в `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// - ```Python - q: Annotated[str | None] = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Annotated[Union[str, None]] = None +``` - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`. @@ -94,17 +113,21 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -120,22 +143,29 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -!!! tip "Подсказка" - При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 +/// tip | "Подсказка" + +При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 + +/// Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -165,22 +195,25 @@ q: str | None = None Но он явно объявляет его как query-параметр. -!!! info "Дополнительная информация" - Запомните, важной частью объявления параметра как необязательного является: +/// info | "Дополнительная информация" + +Запомните, важной частью объявления параметра как необязательного является: - ```Python - = None - ``` +```Python += None +``` - или: +или: - ```Python - = Query(default=None) - ``` +```Python += Query(default=None) +``` - так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. +так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. - `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. +`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. + +/// Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам: @@ -232,81 +265,113 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.9+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="12" +{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +//// Данное регулярное выражение проверяет, что полученное значение параметра: @@ -324,29 +389,41 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note | "Технические детали" -!!! note "Технические детали" - Наличие значения по умолчанию делает параметр необязательным. +Наличие значения по умолчанию делает параметр необязательным. + +/// ## Обязательный параметр @@ -364,75 +441,103 @@ q: Union[str, None] = None Но у нас query-параметр определён как `Query`. Например: -=== "Annotated" +//// tab | Annotated + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +//// tab | без Annotated -=== "без Annotated" +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +//// В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ без Annotated" +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +/// tip | "Подсказка" - !!! tip "Подсказка" - Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. +Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - Лучше будет использовать версию с `Annotated`. 😉 +Лучше будет использовать версию с `Annotated`. 😉 + +/// + +//// ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// -!!! info "Дополнительная информация" - Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` - Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. +//// + +/// info | "Дополнительная информация" + +Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". + +Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. + +/// Таким образом, **FastAPI** определяет, что параметр является обязательным. @@ -442,72 +547,103 @@ q: Union[str, None] = None Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +/// tip | "Подсказка" + +Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. + +/// ### Использование Pydantic's `Required` вместо Ellipsis (`...`) Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 9" +{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="4 10" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="2 9" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} - ``` +/// + +```Python hl_lines="2 8" +{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="2 8" - {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} - ``` +Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. -!!! tip "Подсказка" - Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. +/// ## Множество значений для query-параметра @@ -515,50 +651,71 @@ q: Union[str, None] = None Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.10+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +/// -=== "Python 3.9+ без Annotated" +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Затем, получив такой URL: @@ -579,8 +736,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "Подсказка" - Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. +/// tip | "Подсказка" + +Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. + +/// Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений: @@ -590,35 +750,49 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// Если вы перейдёте по ссылке: @@ -641,31 +815,43 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// note | "Технические детали" - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. -!!! note "Технические детали" - Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. +Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. - Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. +/// ## Больше метаданных @@ -673,86 +859,121 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -!!! note "Технические детали" - Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. +/// note | "Технические детали" - Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. +Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. + +Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. + +/// Вы можете указать название query-параметра, используя параметр `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | "Подсказка" - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// Добавить описание, используя параметр `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +/// + +```Python hl_lines="13" +{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// ## Псевдонимы параметров @@ -772,41 +993,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// ## Устаревшие параметры @@ -816,41 +1053,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="16" +{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="18" +{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// В документации это будет отображено следующим образом: @@ -860,41 +1113,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | "Подсказка" - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="8" +{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index f6e18f971..061f9be04 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -!!! check "Важно" - Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. +/// check | "Важно" + +Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. + +/// ## Преобразование типа параметра запроса Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// В этом случае, если вы сделаете запрос: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Обязательные query-параметры @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// В этом примере, у нас есть 3 параметра запроса: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -!!! tip "Подсказка" - Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. +/// tip | "Подсказка" + +Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 79b3bd067..1fbc4acc0 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы, сначала установите `python-multipart`. +/// info | "Дополнительная информация" - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы, сначала установите `python-multipart`. - Это связано с тем, что загружаемые файлы передаются как данные формы. +Например: `pip install python-multipart`. + +Это связано с тем, что загружаемые файлы передаются как данные формы. + +/// ## Импорт `File` Импортируйте `File` и `UploadFile` из модуля `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | "Подсказка" - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info | "Дополнительная информация" -=== "Python 3.6+ без Annotated" +`File` - это класс, который наследуется непосредственно от `Form`. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info "Дополнительная информация" - `File` - это класс, который наследуется непосредственно от `Form`. +/// tip | "Подсказка" - Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). -!!! tip "Подсказка" - Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). +/// Файлы будут загружены как данные формы. @@ -79,26 +106,35 @@ Определите параметр файла с типом `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -141,11 +177,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "Технические детали `async`" - При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. +/// note | "Технические детали `async`" + +При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. + +/// + +/// note | "Технические детали Starlette" -!!! note "Технические детали Starlette" - **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. +**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. + +/// ## Про данные формы ("Form Data") @@ -153,82 +195,113 @@ contents = myfile.file.read() **FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. +/// note | "Технические детали" + +Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. + +Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. + +Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. + +/// - Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. +/// warning | "Внимание" - Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. +В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. -!!! warning "Внимание" - В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. +Это не является ограничением **FastAPI**, это часть протокола HTTP. - Это не является ограничением **FastAPI**, это часть протокола HTTP. +/// ## Необязательная загрузка файлов Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+" +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Загрузка нескольких файлов @@ -238,76 +311,107 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.9+ без Annotated - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.6+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. -!!! note "Technical Details" - Можно также использовать `from starlette.responses import HTMLResponse`. +/// note | "Technical Details" + +Можно также использовать `from starlette.responses import HTMLResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Загрузка нескольких файлов с дополнительными метаданными Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index a08232ca7..b38962866 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. +/// info | "Дополнительная информация" - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. + +Например: `pip install python-multipart`. + +/// ## Импортируйте `File` и `Form` -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | "Подсказка" - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.6+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="1" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+ без Annotated" +```Python hl_lines="9-11" +{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | "Подсказка" + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -!!! warning "Внимание" - Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. +/// warning | "Внимание" + +Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + +Это не ограничение **Fast API**, это часть протокола HTTP. - Это не ограничение **Fast API**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index fa2bcb7cb..3737f1347 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -!!! info "Дополнительная информация" - Чтобы использовать формы, сначала установите `python-multipart`. +/// info | "Дополнительная информация" - Например, выполните команду `pip install python-multipart`. +Чтобы использовать формы, сначала установите `python-multipart`. + +Например, выполните команду `pip install python-multipart`. + +/// ## Импорт `Form` Импортируйте `Form` из `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. @@ -63,11 +84,17 @@ Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. -!!! info "Дополнительная информация" - `Form` - это класс, который наследуется непосредственно от `Body`. +/// info | "Дополнительная информация" + +`Form` - это класс, который наследуется непосредственно от `Body`. + +/// + +/// tip | "Подсказка" -!!! tip "Подсказка" - Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). +Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). + +/// ## О "полях формы" @@ -75,17 +102,23 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. +/// note | "Технические детали" + +Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. + +Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. + +Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. + +/// - Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. +/// warning | "Предупреждение" - Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. +Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. -!!! warning "Предупреждение" - Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. +Это не ограничение **FastAPI**, это часть протокола HTTP. - Это не ограничение **FastAPI**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 9b9b60dd5..38d185b98 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI будет использовать этот возвращаемый тип для: @@ -53,35 +59,47 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note "Технические детали" - Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. +//// + +/// note | "Технические детали" + +Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. + +/// `response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`. FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -!!! tip "Подсказка" - Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. +/// tip | "Подсказка" + +Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. + +Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. - Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. +/// ### Приоритет `response_model` @@ -95,36 +113,47 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +```Python hl_lines="7 9" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +/// info | "Информация" -!!! info "Информация" - Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. - Используйте `pip install email-validator` - или `pip install pydantic[email]`. +Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. +Используйте `pip install email-validator` +или `pip install pydantic[email]`. + +/// Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -132,52 +161,67 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -!!! danger "Осторожно" - Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. +/// danger | "Осторожно" + +Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. + +/// ## Создание модели для ответа Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -201,17 +245,21 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -277,17 +325,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/response_model/tutorial003_04.py!} +``` + +//// ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -299,17 +351,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -317,23 +373,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -347,23 +409,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial004.py!} +``` + +//// и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -376,16 +444,22 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -!!! info "Информация" - "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. +/// info | "Информация" + +"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. + +/// + +/// info | "Информация" -!!! info "Информация" - Вы также можете использовать: +Вы также можете использовать: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. +как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. + +/// #### Если значение поля отличается от значения по-умолчанию @@ -420,10 +494,13 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -!!! tip "Подсказка" - Значением по умолчанию может быть что угодно, не только `None`. +/// tip | "Подсказка" + +Значением по умолчанию может быть что угодно, не только `None`. + +Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. - Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. +/// ### `response_model_include` и `response_model_exclude` @@ -433,45 +510,59 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -!!! tip "Подсказка" - Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. +/// tip | "Подсказка" + +Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. + +Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. - Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. +То же самое применимо к параметру `response_model_by_alias`. - То же самое применимо к параметру `response_model_by_alias`. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial005.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +/// tip | "Подсказка" -!!! tip "Подсказка" - При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. +При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. - Того же самого можно достичь используя `set(["name", "description"])`. +Того же самого можно достичь используя `set(["name", "description"])`. + +/// #### Что если использовать `list` вместо `set`? Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index b2f9b7704..a36c42d05 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -12,13 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Примечание" - Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. +/// note | "Примечание" + +Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. + +/// Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -!!! info "Информация" - В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. +/// info | "Информация" + +В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. + +/// Это позволит: @@ -27,15 +33,21 @@ -!!! note "Примечание" - Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. +/// note | "Примечание" + +Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. + +FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. - FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. +/// ## Об HTTP кодах статуса ответа -!!! note "Примечание" - Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. +/// note | "Примечание" + +Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. + +/// В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа. @@ -54,8 +66,11 @@ * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -!!! tip "Подсказка" - Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. +/// tip | "Подсказка" + +Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. + +/// ## Краткие обозначения для запоминания названий кодов @@ -79,10 +94,13 @@ -!!! note "Технические детали" - Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. +/// note | "Технические детали" + +Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. + +**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. - **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. +/// ## Изменение кода статуса по умолчанию diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index e1011805a..1b216de3a 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. -!!! tip Подсказка - Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. +/// tip | Подсказка + +Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. + +Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. - Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. +/// ## Дополнительные аргументы поля `Field` @@ -33,20 +40,27 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +/// warning | Внимание -!!! warning Внимание - Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. +Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. + +/// ## Использование `example` и `examples` в OpenAPI @@ -66,41 +80,57 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23-28" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Заметка - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +/// tip | Заметка - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Аргумент "example" в UI документации @@ -121,41 +151,57 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +```Python hl_lines="24-50" +{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip | Заметка - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +Рекомендуется использовать версию с `Annotated`, если это возможно. - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="19-45" +{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip | Заметка + +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="21-47" +{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// ### Аргумент "examples" в UI документации @@ -165,10 +211,13 @@ ## Технические Детали -!!! warning Внимание - Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. +/// warning | Внимание + +Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. + +Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. - Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. +/// Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index fdeccc01a..444a06915 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ Скопируйте пример в файл `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +/// tip | "Подсказка" -=== "Python 3.8+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` +//// ## Запуск -!!! info "Дополнительная информация" - Вначале, установите библиотеку `python-multipart`. +/// info | "Дополнительная информация" - А именно: `pip install python-multipart`. +Вначале, установите библиотеку `python-multipart`. - Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. +А именно: `pip install python-multipart`. + +Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. + +/// Запустите ваш сервер: @@ -71,17 +82,23 @@ $ uvicorn main:app --reload -!!! check "Кнопка авторизации!" - У вас уже появилась новая кнопка "Authorize". +/// check | "Кнопка авторизации!" + +У вас уже появилась новая кнопка "Authorize". - А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. +А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. + +/// При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля): -!!! note "Технические детали" - Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. +/// note | "Технические детали" + +Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. + +/// Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API. @@ -123,51 +140,69 @@ OAuth2 был разработан для того, чтобы бэкэнд ил В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. -!!! info "Дополнительная информация" - Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. +/// info | "Дополнительная информация" + +Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. + +И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. - И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. +В этом случае **FastAPI** также предоставляет инструменты для его реализации. - В этом случае **FastAPI** также предоставляет инструменты для его реализации. +/// При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | "Подсказка" - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="6" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip | "Подсказка" - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. -!!! tip "Подсказка" - Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. +Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. - Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. +Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. - Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +/// Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API. Вскоре мы создадим и саму операцию пути. -!!! info "Дополнительная информация" - Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. +/// info | "Дополнительная информация" + +Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. + +Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. - Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. +/// Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой". @@ -183,35 +218,47 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../../docs_src/security/tutorial001.py!} +``` + +//// Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. **FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). -!!! info "Технические детали" - **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. +/// info | "Технические детали" + +**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. + +Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. - Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. +/// ## Что он делает diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index d5fe4e76f..bd512fde3 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -!!! tip "Подсказка" - В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) +/// tip | "Подсказка" +В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -!!! tip "Подсказка" - Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. +/// tip | "Подсказка" + +Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. + +Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. - Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. +/// ## Преимущества **FastAPI** diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index afe2075d9..ccddae249 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Технические детали" - Вы также можете использовать `from starlette.staticfiles import StaticFiles`. +/// note | "Технические детали" - **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. +Вы также можете использовать `from starlette.staticfiles import StaticFiles`. + +**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. + +/// ### Что такое "Монтирование" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index 4772660df..efefbfb01 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## Использование класса `TestClient` -!!! info "Информация" - Для использования класса `TestClient` необходимо установить библиотеку `httpx`. +/// info | "Информация" - Например, так: `pip install httpx`. +Для использования класса `TestClient` необходимо установить библиотеку `httpx`. + +Например, так: `pip install httpx`. + +/// Импортируйте `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "Подсказка" - Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. +/// tip | "Подсказка" + +Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. + +И вызов клиента также осуществляется без `await`. + +Это позволяет вам использовать `pytest` без лишних усложнений. + +/// + +/// note | "Технические детали" + +Также можно написать `from starlette.testclient import TestClient`. - И вызов клиента также осуществляется без `await`. +**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. - Это позволяет вам использовать `pytest` без лишних усложнений. +/// -!!! note "Технические детали" - Также можно написать `from starlette.testclient import TestClient`. +/// tip | "Подсказка" - **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. +Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. -!!! tip "Подсказка" - Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. +/// ## Разделение тестов и приложения @@ -110,41 +122,57 @@ Обе *операции пути* требуют наличия в запросе заголовка `X-Token`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | "Подсказка" - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +По возможности используйте версию с `Annotated`. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | "Подсказка" + +По возможности используйте версию с `Annotated`. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Расширенный файл тестов @@ -168,10 +196,13 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX. -!!! info "Информация" - Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. +/// info | "Информация" + +Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. + +Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. - Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. +/// ## Запуск тестов diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md index c0a566d12..6c057162e 100644 --- a/docs/tr/docs/advanced/index.md +++ b/docs/tr/docs/advanced/index.md @@ -6,10 +6,13 @@ İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. -!!! tip "İpucu" - Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. +/// tip | "İpucu" - Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// ## Önce Öğreticiyi Okuyun diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md index 89a431687..227674bd4 100644 --- a/docs/tr/docs/advanced/security/index.md +++ b/docs/tr/docs/advanced/security/index.md @@ -4,10 +4,13 @@ [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. -!!! tip "İpucu" - Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. +/// tip | "İpucu" - Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// ## Önce Öğreticiyi Okuyun diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index cdd5b7ae5..59a2499e2 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -8,5 +8,8 @@ Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e ba {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "Not" - Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. +/// note | "Not" + +Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. + +/// diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 462d8b304..bd668ca45 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -30,11 +30,17 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p **Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. -!!! note "Not" - Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. +/// note | "Not" -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. +Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. + +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. + +/// ### Flask @@ -50,10 +56,13 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" - Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. +Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. + +Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. + +/// ### Requests @@ -89,10 +98,13 @@ def read_url(): `requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - * Basit ve sezgisel bir API'ya sahip olmalı. - * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. - * Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +* Basit ve sezgisel bir API'ya sahip olmalı. +* HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. +* Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. + +/// ### Swagger / OpenAPI @@ -106,15 +118,18 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. + +Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: - Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: +* Swagger UI +* ReDoc - * Swagger UI - * ReDoc +Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. - Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. +/// ### Flask REST framework'leri @@ -132,8 +147,11 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. + +/// ### Webargs @@ -145,11 +163,17 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. -!!! info "Bilgi" - Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. +/// info | "Bilgi" + +Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" + +Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. + +/// ### APISpec @@ -167,11 +191,17 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. -!!! info "Bilgi" - APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. +/// info | "Bilgi" + +APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. + +/// + +/// check | "**FastAPI**'a nasıl ilham verdi?" -!!! check "**FastAPI**'a nasıl ilham verdi?" - API'lar için açık standart desteği olmalı (OpenAPI gibi). +API'lar için açık standart desteği olmalı (OpenAPI gibi). + +/// ### Flask-apispec @@ -193,11 +223,17 @@ Bunu kullanmak, bir kaç NestJS (and Angular) @@ -213,24 +249,33 @@ Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından, İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Güzel bir editör desteği için Python tiplerini kullanmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Güzel bir editör desteği için Python tiplerini kullanmalı. - Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. +Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. + +/// ### Sanic Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti. -!!! note "Teknik detaylar" - İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. +/// note | "Teknik detaylar" + +İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. + +Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. - Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Uçuk performans sağlayacak bir yol bulmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" - Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) +Uçuk performans sağlayacak bir yol bulmalı. + +Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) + +/// ### Falcon @@ -240,12 +285,15 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Harika bir performans'a sahip olmanın yollarını bulmalı. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Harika bir performans'a sahip olmanın yollarını bulmalı. - Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. +Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. - FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. +FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. + +/// ### Molten @@ -263,10 +311,13 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. +/// check | "**FastAPI**'a nasıl ilham oldu?" + +Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. + +Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. - Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. +/// ### Hug @@ -282,15 +333,21 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. -!!! info "Bilgi" - Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. +/// info | "Bilgi" + +Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. + +/// + +/// check | "**FastAPI**'a nasıl ilham oldu?" -!!! check "**FastAPI**'a nasıl ilham oldu?" - Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. +Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. - **FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. +**FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. - **FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. +**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. + +/// ### APIStar (<= 0.5) @@ -316,23 +373,29 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. -!!! info "Bilgi" - APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: +/// info | "Bilgi" + +APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: + +* Django REST Framework +* **FastAPI**'ın da dayandığı Starlette +* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn - * Django REST Framework - * **FastAPI**'ın da dayandığı Starlette - * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Var oldu. +/// check | "**FastAPI**'a nasıl ilham oldu?" - Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. +Var oldu. - Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. +Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. - Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. +Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. - Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. +Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. + +Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. + +/// ## **FastAPI** Tarafından Kullanılanlar @@ -344,10 +407,13 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. -!!! check "**FastAPI** nerede kullanıyor?" - Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! +/// check | "**FastAPI** nerede kullanıyor?" + +Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! - **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. +**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. + +/// ### Starlette @@ -376,18 +442,23 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. -!!! note "Teknik Detaylar" - ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. +/// note | "Teknik Detaylar" + +ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. + +Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. - Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. +/// -!!! check "**FastAPI** nerede kullanıyor?" +/// check | "**FastAPI** nerede kullanıyor?" - Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. +Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. - `FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! +`FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! - Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. +Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. + +/// ### Uvicorn @@ -397,12 +468,15 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. -!!! check "**FastAPI** neden tavsiye ediyor?" - **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! +/// check | "**FastAPI** neden tavsiye ediyor?" + +**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! + +Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! - Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! +Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. - Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. +/// ## Karşılaştırma ve Hız diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index c7bedffd1..0d463a2f0 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "Not" - Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. +/// note | "Not" + +Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. + +/// --- @@ -363,12 +366,15 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p ## Çok Teknik Detaylar -!!! warning - Muhtemelen burayı atlayabilirsiniz. +/// warning + +Muhtemelen burayı atlayabilirsiniz. + +Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. - Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. +Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. - Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. +/// ### Path fonksiyonu diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md index 209ab922c..6e8af4025 100644 --- a/docs/tr/docs/external-links.md +++ b/docs/tr/docs/external-links.md @@ -6,8 +6,11 @@ Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. -!!! tip "İpucu" - Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. +/// tip | "İpucu" + +Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 1cda8c7fb..5d40b1086 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -67,10 +67,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` şu anlama geliyor: +/// info - Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` şu anlama geliyor: + +Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor desteği diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md index 8ece29515..798adca61 100644 --- a/docs/tr/docs/how-to/index.md +++ b/docs/tr/docs/how-to/index.md @@ -6,6 +6,8 @@ Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. -!!! tip "İpucu" +/// tip | "İpucu" - **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. +**FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. + +/// diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index ac3111136..b8b880c6d 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,8 +12,11 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -!!! note "Not" - Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. +/// note | "Not" + +Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. + +/// ## Motivasyon @@ -172,10 +175,13 @@ Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli para {!../../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Ipucu" - Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. +/// tip | "Ipucu" + +Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. + +Bu durumda `str`, `List`e iletilen tür parametresidir. - Bu durumda `str`, `List`e iletilen tür parametresidir. +/// Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir". @@ -281,8 +287,11 @@ Resmi Pydantic dokümanlarından alınmıştır: {!../../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Daha fazla şey öğrenmek için Pydantic'i takip edin. +/// info + +Daha fazla şey öğrenmek için Pydantic'i takip edin. + +/// **FastAPI** tamamen Pydantic'e dayanmaktadır. @@ -310,5 +319,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak. -!!! info - Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. +/// info + +Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. + +/// diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 4a66f26eb..807f85e8a 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Öncelikle, `Cookie`'yi projenize dahil edin: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +/// tip | "İpucu" - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "İpucu" + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie` Parametrelerini Tanımlayın @@ -48,49 +64,71 @@ İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "İpucu" + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | "İpucu" -=== "Python 3.8+" +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Teknik Detaylar" -=== "Python 3.8+ non-Annotated" +`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. - !!! tip "İpucu" - Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. +Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Teknik Detaylar" - `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. +/// info | "Bilgi" - Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. +Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. -!!! info "Bilgi" - Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. +/// ## Özet diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index e66f73034..76c035992 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note "Not" - `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: +/// note | "Not" - * `main`: dosya olan `main.py` (yani Python "modülü"). - * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. - * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: + +* `main`: dosya olan `main.py` (yani Python "modülü"). +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. + +/// Çıktı olarak şöyle bir satır ile karşılaşacaksınız: @@ -136,10 +139,13 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. -!!! note "Teknik Detaylar" - `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. +/// note | "Teknik Detaylar" + +`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. - Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. +Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. + +/// ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Bilgi" - "Yol" genellikle "endpoint" veya "route" olarak adlandırılır. +/// info | "Bilgi" + +"Yol" genellikle "endpoint" veya "route" olarak adlandırılır. + +/// Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir. @@ -250,16 +259,19 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. * get operasyonu ile * `/` yoluna gelen istekler -!!! info "`@decorator` Bilgisi" - Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. +/// info | "`@decorator` Bilgisi" - Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. +Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. - Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. +Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. - Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. +Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. - Bu bir **yol operasyonu dekoratörüdür**. +Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. + +Bu bir **yol operasyonu dekoratörüdür**. + +/// Ayrıca diğer operasyonları da kullanabilirsiniz: @@ -274,14 +286,17 @@ Daha az kullanılanları da kullanabilirsiniz: * `@app.patch()` * `@app.trace()` -!!! tip "İpucu" - Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. +/// tip | "İpucu" + +Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. - **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. +**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. - Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. +Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. - Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. +Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. + +/// ### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın @@ -309,8 +324,11 @@ Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirs {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Not" - Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. +/// note | "Not" + +Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. + +/// ### Adım 5: İçeriği Geri Döndürün diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index c19023645..d36242083 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -24,8 +24,11 @@ Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiy Bu durumda, `item_id` bir `int` olarak tanımlanacaktır. -!!! check "Ek bilgi" - Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. +/// check | "Ek bilgi" + +Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. + +/// ## Veri Dönüşümü @@ -35,10 +38,13 @@ Eğer bu örneği çalıştırıp tarayıcınızda "ayrıştırma" özelliği sağlar. - Bu tanımlamayla birlikte, **FastAPI** size otomatik istek "ayrıştırma" özelliği sağlar. +/// ## Veri Doğrulama @@ -65,12 +71,15 @@ Eğer tarayıcınızda http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. -!!! check "Ek bilgi" - Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. +/// check | "Ek bilgi" - Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. +Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. - Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. +Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. + +Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. + +/// ## Dokümantasyon @@ -78,10 +87,13 @@ Ayrıca, tarayıcınızı -!!! check "Ek bilgi" - Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. +/// check | "Ek bilgi" + +Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. + +Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. - Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. +/// ## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon @@ -141,11 +153,17 @@ Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Bilgi" - 3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. +/// info | "Bilgi" -!!! tip "İpucu" - Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. +3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. + +/// + +/// tip | "İpucu" + +Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. + +/// ### Bir *Yol Parametresi* Tanımlayalım @@ -181,8 +199,11 @@ Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration {!../../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "İpucu" - `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. +/// tip | "İpucu" + +`"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. + +/// #### *Enumeration Üyelerini* Döndürelim @@ -235,10 +256,13 @@ Böylece şunun gibi bir kullanım yapabilirsiniz: {!../../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "İpucu" - Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. +/// tip | "İpucu" + +Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. + +Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. - Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. +/// ## Özet diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index 682f8332c..bf66dbe74 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -63,38 +63,49 @@ Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. -!!! check "Ek bilgi" - Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. +/// check | "Ek bilgi" + +Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +/// ## Sorgu Parametresi Tip Dönüşümü Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Bu durumda, eğer şu adrese giderseniz: @@ -137,17 +148,21 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Zorunlu Sorgu Parametreleri @@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// Bu durumda, 3 tane sorgu parametresi var olacaktır: @@ -223,5 +242,8 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `skip`, varsayılan değeri `0` olan bir `int`. * `limit`, isteğe bağlı bir `int`. -!!! tip "İpucu" - Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. +/// tip | "İpucu" + +Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + +/// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 2728b6164..8e8ccfba4 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. -!!! info "Bilgi" - Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. +/// info | "Bilgi" - Örneğin `pip install python-multipart`. +Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. + +Örneğin `pip install python-multipart`. + +/// ## `Form` Sınıfını Projenize Dahil Edin `Form` sınıfını `fastapi`'den projenize dahil edin: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## `Form` Parametrelerini Tanımlayın Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_forms/tutorial001.py!} +``` + +//// Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. @@ -63,11 +84,17 @@ Bu spesifikasyon form alanlar `Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. -!!! info "Bilgi" - `Form` doğrudan `Body` sınıfını miras alan bir sınıftır. +/// info | "Bilgi" + +`Form` doğrudan `Body` sınıfını miras alan bir sınıftır. + +/// + +/// tip | "İpucu" -!!! tip "İpucu" - Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. +Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. + +/// ## "Form Alanları" Hakkında @@ -75,17 +102,23 @@ HTML formlarının (`
`) verileri sunucuya gönderirken JSON'dan far **FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. -!!! note "Teknik Detaylar" - Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. +/// note | "Teknik Detaylar" + +Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. + +Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. + +Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST sayfasını ziyaret edebilirsiniz. + +/// - Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. +/// warning | "Uyarı" - Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST sayfasını ziyaret edebilirsiniz. +*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. -!!! warning "Uyarı" - *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. +Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. - Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. +/// ## Özet diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index 00c833686..b82be611f 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Teknik Detaylar" - Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. +/// note | "Teknik Detaylar" - **FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. +Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. + +**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. + +/// ### Bağlama (Mounting) Nedir? diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index 16cc0d875..eb48d6be7 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,12 +30,17 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -!!! note "Примітка" - Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. +/// note | "Примітка" +Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. -!!! check "Надихнуло **FastAPI** на" - Мати автоматичний веб-інтерфейс документації API. +/// + +/// check | "Надихнуло **FastAPI** на" + +Мати автоматичний веб-інтерфейс документації API. + +/// ### Flask @@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -!!! check "Надихнуло **FastAPI** на" - Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. +/// check | "Надихнуло **FastAPI** на" - Мати просту та легку у використанні систему маршрутизації. +Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. + Мати просту та легку у використанні систему маршрутизації. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -!!! check "Надихнуло **FastAPI** на" - * Майте простий та інтуїтивно зрозумілий API. - * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. - * Розумні параметри за замовчуванням, але потужні налаштування. +/// check | "Надихнуло **FastAPI** на" + +* Майте простий та інтуїтивно зрозумілий API. + * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. + * Розумні параметри за замовчуванням, але потужні налаштування. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -!!! check "Надихнуло **FastAPI** на" - Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. +/// check | "Надихнуло **FastAPI** на" + +Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. - Інтегрувати інструменти інтерфейсу на основі стандартів: + Інтегрувати інструменти інтерфейсу на основі стандартів: - * Інтерфейс Swagger - * ReDoc + * Інтерфейс Swagger + * ReDoc - Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + +/// ### Фреймворки REST для Flask @@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -!!! check "Надихнуло **FastAPI** на" - Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. +/// check | "Надихнуло **FastAPI** на" + +Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. + +/// ### Webargs @@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -!!! info "Інформація" - Webargs був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +Webargs був створений тими ж розробниками Marshmallow. + +/// + +/// check | "Надихнуло **FastAPI** на" -!!! check "Надихнуло **FastAPI** на" - Мати автоматичну перевірку даних вхідного запиту. +Мати автоматичну перевірку даних вхідного запиту. + +/// ### APISpec @@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -!!! info "Інформація" - APISpec був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +APISpec був створений тими ж розробниками Marshmallow. + +/// +/// check | "Надихнуло **FastAPI** на" -!!! check "Надихнуло **FastAPI** на" - Підтримувати відкритий стандарт API, OpenAPI. +Підтримувати відкритий стандарт API, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -!!! info "Інформація" - Flask-apispec був створений тими ж розробниками Marshmallow. +/// info | "Інформація" + +Flask-apispec був створений тими ж розробниками Marshmallow. + +/// -!!! check "Надихнуло **FastAPI** на" - Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. +/// check | "Надихнуло **FastAPI** на" + +Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. + +/// ### NestJS (та Angular) @@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -!!! check "Надихнуло **FastAPI** на" - Використовувати типи Python, щоб мати чудову підтримку редактора. +/// check | "Надихнуло **FastAPI** на" + +Використовувати типи Python, щоб мати чудову підтримку редактора. - Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + +/// ### Sanic Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -!!! note "Технічні деталі" - Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. +/// note | "Технічні деталі" + +Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. - Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. + Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. -!!! check "Надихнуло **FastAPI** на" - Знайти спосіб отримати божевільну продуктивність. +/// - Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). +/// check | "Надихнуло **FastAPI** на" + +Знайти спосіб отримати божевільну продуктивність. + + Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). + +/// ### Falcon @@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -!!! check "Надихнуло **FastAPI** на" - Знайти способи отримати чудову продуктивність. +/// check | "Надихнуло **FastAPI** на" - Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. +Знайти способи отримати чудову продуктивність. - Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. + + Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + +/// ### Molten @@ -269,10 +313,13 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -!!! check "Надихнуло **FastAPI** на" - Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. +/// check | "Надихнуло **FastAPI** на" + +Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. - Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + +/// ### Hug @@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -!!! info "Інформація" - Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. +/// info | "Інформація" + +Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. + +/// -!!! check "Надихнуло **FastAPI** на" - Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. +/// check | "Надихнуло **FastAPI** на" - Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. +Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. - Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. + + Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + +/// ### APIStar (<= 0,5) @@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -!!! info "Інформація" - APIStar створив Том Крісті. Той самий хлопець, який створив: +/// info | "Інформація" + +APIStar створив Том Крісті. Той самий хлопець, який створив: - * Django REST Framework - * Starlette (на якому базується **FastAPI**) - * Uvicorn (використовується Starlette і **FastAPI**) + * Django REST Framework + * Starlette (на якому базується **FastAPI**) + * Uvicorn (використовується Starlette і **FastAPI**) -!!! check "Надихнуло **FastAPI** на" - Існувати. +/// - Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. +/// check | "Надихнуло **FastAPI** на" - І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. +Існувати. - Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. + + І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. + + Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + +/// ## Використовується **FastAPI** @@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -!!! check "**FastAPI** використовує його для" - Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). +/// check | "**FastAPI** використовує його для" - Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. +Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). + + Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. + +/// ### Starlette @@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -!!! note "Технічні деталі" - ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. +/// note | "Технічні деталі" + +ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. - Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. + Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. -!!! check "**FastAPI** використовує його для" - Керування всіма основними веб-частинами. Додавання функцій зверху. +/// - Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. +/// check | "**FastAPI** використовує його для" - Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. +Керування всіма основними веб-частинами. Додавання функцій зверху. + + Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. + + Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. + +/// ### Uvicorn @@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -!!! check "**FastAPI** рекомендує це як" - Основний веб-сервер для запуску програм **FastAPI**. +/// check | "**FastAPI** рекомендує це як" + +Основний веб-сервер для запуску програм **FastAPI**. + + Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. - Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. + Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. - Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. +/// ## Орієнтири та швидкість diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index d0adadff3..511a5264a 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -12,8 +12,11 @@ Python підтримує додаткові "підказки типу" ("type Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них. -!!! note - Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. +/// note + +Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. + +/// ## Мотивація @@ -164,45 +167,55 @@ John Doe Наприклад, давайте визначимо змінну, яка буде `list` із `str`. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +З модуля `typing`, імпортуємо `List` (з великої літери `L`): + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - З модуля `typing`, імпортуємо `List` (з великої літери `L`): +Як тип вкажемо `List`, який ви імпортували з `typing`. - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +//// - Як тип вкажемо `List`, який ви імпортували з `typing`. +//// tab | Python 3.9 і вище - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Як тип вкажемо `list`. -=== "Python 3.9 і вище" +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` - Як тип вкажемо `list`. +//// - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +/// info - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +Ці внутрішні типи в квадратних дужках називаються "параметрами типу". -!!! info - Ці внутрішні типи в квадратних дужках називаються "параметрами типу". +У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). - У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). +/// Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`". -!!! tip - Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. +/// tip + +Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. + +/// Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку: @@ -218,17 +231,21 @@ John Doe Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.9 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// Це означає: @@ -243,17 +260,21 @@ John Doe Другий параметр типу для значення у `dict`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// Це означає: @@ -269,17 +290,21 @@ John Doe У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`). -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// В обох випадках це означає, що `item` може бути `int` або `str`. @@ -299,69 +324,81 @@ John Doe Це також означає, що в Python 3.10 ви можете використовувати `Something | None`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8 і вище - альтернатива -=== "Python 3.8 і вище - альтернатива" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### Generic типи Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...та інші. + +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...та інші. +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +І те саме, що й у Python 3.8, із модуля `typing`: - І те саме, що й у Python 3.8, із модуля `typing`: +* `Union` +* `Optional` +* ...та інші. - * `Union` - * `Optional` - * ...та інші. +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - І те саме, що й у Python 3.8, із модуля `typing`: +І те саме, що й у Python 3.8, із модуля `typing`: - * `Union` - * `Optional` (так само як у Python 3.8) - * ...та інші. +* `Union` +* `Optional` (так само як у Python 3.8) +* ...та інші. - У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. +У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. + +//// ### Класи як типи @@ -397,26 +434,35 @@ John Doe Приклад з документації Pydantic: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | Python 3.9 і вище + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.10 і вище - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - Щоб дізнатись більше про Pydantic, перегляньте його документацію. +Щоб дізнатись більше про Pydantic, перегляньте його документацію. + +/// **FastAPI** повністю базується на Pydantic. @@ -444,5 +490,8 @@ John Doe Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас. -!!! info - Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. +/// info + +Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. + +/// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index eee993cbe..e4d5b1fad 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ Спочатку вам потрібно імпортувати це: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Варто користуватись `Annotated` версією, якщо це можливо. -!!! warning - Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). +/// + +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо. + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning + +Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). + +/// ## Оголошення атрибутів моделі Ви можете використовувати `Field` з атрибутами моделі: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Варто користуватись `Annotated` версією, якщо це можливо.. - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо.. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -!!! note "Технічні деталі" - Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. +/// note | "Технічні деталі" - І `Field` від Pydantic також повертає екземпляр `FieldInfo`. +Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. - `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. +І `Field` від Pydantic також повертає екземпляр `FieldInfo`. - Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. +`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. -!!! tip - Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. +Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. + +/// + +/// tip + +Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. + +/// ## Додавання додаткової інформації @@ -105,9 +146,12 @@ Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. -!!! warning - Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. - Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. +/// warning + +Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. +Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +/// ## Підсумок diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 11e94e929..50fd76f84 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -8,28 +8,35 @@ Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами. -!!! info - Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. +/// info - Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. +Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. - Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. +Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. + +Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. + +/// ## Імпортуйте `BaseModel` від Pydantic Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## Створіть свою модель даних @@ -37,17 +44,21 @@ Використовуйте стандартні типи Python для всіх атрибутів: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -75,17 +86,21 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -134,32 +149,39 @@ -!!! tip - Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. +/// tip + +Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. - Він покращує підтримку редакторів для моделей Pydantic за допомогою: +Він покращує підтримку редакторів для моделей Pydantic за допомогою: - * автозаповнення - * перевірки типу - * рефакторингу - * пошуку - * інспекції +* автозаповнення +* перевірки типу +* рефакторингу +* пошуку +* інспекції + +/// ## Використовуйте модель Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## Тіло запиту + параметри шляху @@ -167,17 +189,21 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## Тіло запиту + шлях + параметри запиту @@ -185,17 +211,21 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// Параметри функції будуть розпізнаватися наступним чином: @@ -203,10 +233,13 @@ * Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**. * Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту. -!!! note - FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". +/// note + +FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". + +`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. - `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. +/// ## Без Pydantic diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 199b93839..4720a42ba 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Спочатку імпортуйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Визначення параметрів `Cookie` @@ -48,48 +64,70 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | "Технічні Деталі" -=== "Python 3.8+ non-Annotated" +`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. +Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// info -!!! note "Технічні Деталі" - `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. - Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. +Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. -!!! info - Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. +/// ## Підсумки diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 49321ff11..9ef8d5c5d 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. @@ -38,5 +42,8 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -!!! note "Примітка" - `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. +/// note | "Примітка" + +`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. + +/// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 01852803a..54cbd4b00 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 725677e42..784da65f5 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -163,10 +163,13 @@ OpenAPI описує схему для вашого API. І ця схема вк `FastAPI` це клас у Python, який надає всю функціональність для API. -!!! note "Технічні деталі" - `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. +/// note | "Технічні деталі" - Ви також можете використовувати всю функціональність Starlette у `FastAPI`. +`FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + +Ви також можете використовувати всю функціональність Starlette у `FastAPI`. + +/// ### Крок 2: створюємо екземпляр `FastAPI` @@ -195,8 +198,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Додаткова інформація" - "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). +/// info | "Додаткова інформація" + +"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). + +/// При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів". #### Operation @@ -244,16 +250,19 @@ https://example.com/items/foo * шлях `/` * використовуючи get операцію -!!! info "`@decorator` Додаткова інформація" - Синтаксис `@something` у Python називається "декоратором". +/// info | "`@decorator` Додаткова інформація" + +Синтаксис `@something` у Python називається "декоратором". - Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). +Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). - "Декоратор" приймає функцію нижче і виконує з нею якусь дію. +"Декоратор" приймає функцію нижче і виконує з нею якусь дію. - У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. +У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. - Це і є "декоратор операції шляху (path operation decorator)". +Це і є "декоратор операції шляху (path operation decorator)". + +/// Можна також використовувати операції: @@ -268,15 +277,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Порада" - Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. +/// tip | "Порада" + +Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. - **FastAPI** не нав'язує жодного певного значення для кожного методу. +**FastAPI** не нав'язує жодного певного значення для кожного методу. - Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. +Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. - Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. +Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. +/// ### Крок 4: визначте **функцію операції шляху (path operation function)** @@ -304,8 +315,11 @@ FastAPI викликатиме її щоразу, коли отримає зап {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Примітка" - Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note | "Примітка" + +Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Крок 5: поверніть результат diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md index e5bae74bc..92c3e77a3 100644 --- a/docs/uk/docs/tutorial/index.md +++ b/docs/uk/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код. -!!! note - Ви також можете встановити його частина за частиною. +/// note - Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: +Ви також можете встановити його частина за частиною. - ``` - pip install fastapi - ``` +Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: - Також встановіть `uvicorn`, щоб він працював як сервер: +``` +pip install fastapi +``` + +Також встановіть `uvicorn`, щоб він працював як сервер: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +І те саме для кожної з опціональних залежностей, які ви хочете використовувати. - І те саме для кожної з опціональних залежностей, які ви хочете використовувати. +/// ## Розширений посібник користувача diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 9edb1c8fa..2220d9fa5 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` nghĩa là: +/// info - Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` nghĩa là: + +Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Được hỗ trợ từ các trình soạn thảo diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 84d14de55..99d1d207f 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -12,8 +12,11 @@ Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các tr Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng. -!!! note - Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. +/// note + +Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. + +/// ## Động lực @@ -170,45 +173,55 @@ Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, s Ví dụ, hãy định nghĩa một biến là `list` các `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ - Khai báo biến với cùng dấu hai chấm (`:`). +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự kiểu dữ liệu `list`. +Tương tự kiểu dữ liệu `list`. - Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - Từ `typing`, import `List` (với chữ cái `L` viết hoa): +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Từ `typing`, import `List` (với chữ cái `L` viết hoa): - Khai báo biến với cùng dấu hai chấm (`:`). +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. +Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. - Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! info - Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". +/// info - Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). +Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". + +Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). + +/// Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`". -!!! tip - Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. +/// tip + +Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. + +/// Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách: @@ -224,17 +237,21 @@ Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp s Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// Điều này có nghĩa là: @@ -249,17 +266,21 @@ Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`. Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Điều này có nghĩa là: @@ -278,17 +299,21 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`. @@ -308,23 +333,29 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ alternative" +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### Sử dụng `Union` hay `Optional` @@ -372,47 +403,53 @@ Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optiona Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): - Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Và tương tự với Python 3.6, từ mô đun `typing`: - Và tương tự với Python 3.6, từ mô đun `typing`: +* `Union` +* `Optional` (tương tự như Python 3.6) +* ...và các kiểu dữ liệu khác. - * `Union` - * `Optional` (tương tự như Python 3.6) - * ...và các kiểu dữ liệu khác. +Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. - Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): +Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - Và tương tự với Python 3.6, từ mô đun `typing`: +Và tương tự với Python 3.6, từ mô đun `typing`: - * `Union` - * `Optional` - * ...and others. +* `Union` +* `Optional` +* ...and others. -=== "Python 3.8+" +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...và các kiểu khác. +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...và các kiểu khác. + +//// ### Lớp như kiểu dữ liệu @@ -452,56 +489,71 @@ Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo Một ví dụ từ tài liệu chính thức của Pydantic: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. -!!! info - Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. +/// **FastAPI** được dựa hoàn toàn trên Pydantic. Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. +/// tip + +Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. +/// ## Type Hints với Metadata Annotations Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` - Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. - Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. +Nó đã được cài đặt sẵng cùng với **FastAPI**. - Nó đã được cài đặt sẵng cùng với **FastAPI**. +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`. @@ -514,10 +566,13 @@ Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm. -!!! tip - Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ +/// tip - Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 +Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ + +Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 + +/// ## Các gợi ý kiểu dữ liệu trong **FastAPI** @@ -541,5 +596,8 @@ Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạ Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn. -!!! info - Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. +/// info + +Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. + +/// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index 712f00852..ce808eb91 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -24,12 +24,15 @@ $ uvicorn main:app --reload -!!! note - Câu lệnh `uvicorn main:app` được giải thích như sau: +/// note - * `main`: tệp tin `main.py` (một Python "mô đun"). - * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. - * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. +Câu lệnh `uvicorn main:app` được giải thích như sau: + +* `main`: tệp tin `main.py` (một Python "mô đun"). +* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. +* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. + +/// Trong output, có một dòng giống như: @@ -136,10 +139,13 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. -!!! note "Chi tiết kĩ thuật" - `FastAPI` là một class kế thừa trực tiếp `Starlette`. +/// note | "Chi tiết kĩ thuật" + +`FastAPI` là một class kế thừa trực tiếp `Starlette`. - Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. +Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. + +/// ### Bước 2: Tạo một `FastAPI` "instance" @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". +/// info + +Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". + +/// Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên". @@ -250,16 +259,19 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**". * đường dẫn `/` * sử dụng một toán tửget -!!! info Thông tin về "`@decorator`" - Cú pháp `@something` trong Python được gọi là một "decorator". +/// info | Thông tin về "`@decorator`" - Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). +Cú pháp `@something` trong Python được gọi là một "decorator". - Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. +Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). - Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. +Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. - Nó là một "**decorator đường dẫn toán tử**". +Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. + +Nó là một "**decorator đường dẫn toán tử**". + +/// Bạn cũng có thể sử dụng với các toán tử khác: @@ -274,14 +286,17 @@ Và nhiều hơn với các toán tử còn lại: * `@app.patch()` * `@app.trace()` -!!! tip - Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. +/// tip + +Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. - **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. +**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. - Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. +Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. - Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. +Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. + +/// ### Step 4: Định nghĩa **hàm cho đường dẫn toán tử** @@ -309,8 +324,11 @@ Bạn cũng có thể định nghĩa nó như là một hàm thông thường th {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Bước 5: Nội dung trả về diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md index e8a93fe40..dfeeed8c5 100644 --- a/docs/vi/docs/tutorial/index.md +++ b/docs/vi/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn. -!!! note - Bạn cũng có thể cài đặt nó từng phần. +/// note - Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: +Bạn cũng có thể cài đặt nó từng phần. - ``` - pip install fastapi - ``` +Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: - Cũng cài đặt `uvicorn` để làm việc như một server: +``` +pip install fastapi +``` + +Cũng cài đặt `uvicorn` để làm việc như một server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. - Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. +/// ## Hướng dẫn nâng cao diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md index cbd5a6cde..c59e8e71c 100644 --- a/docs/zh-hant/docs/benchmarks.md +++ b/docs/zh-hant/docs/benchmarks.md @@ -1,34 +1,34 @@ -# 基準測試 - -由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 - -但是在查看基準得分和對比時,請注意以下幾點。 - -## 基準測試和速度 - -當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 - -具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 - -該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 - -層次結構如下: - -* **Uvicorn**:ASGI 伺服器 - * **Starlette**:(使用 Uvicorn)一個網頁微框架 - * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 - -* **Uvicorn**: - * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 - * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 - * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 -* **Starlette**: - * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 - * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 - * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 -* **FastAPI**: - * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 - * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 - * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 - * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 - * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 +# 基準測試 + +由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 + +但是在查看基準得分和對比時,請注意以下幾點。 + +## 基準測試和速度 + +當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 + +具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 + +該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 + +層次結構如下: + +* **Uvicorn**:ASGI 伺服器 + * **Starlette**:(使用 Uvicorn)一個網頁微框架 + * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 + +* **Uvicorn**: + * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 + * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 + * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 +* **Starlette**: + * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 + * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 + * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 +* **FastAPI**: + * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 + * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 + * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 + * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 + * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md index cc671cacf..99277b419 100644 --- a/docs/zh-hant/docs/fastapi-people.md +++ b/docs/zh-hant/docs/fastapi-people.md @@ -45,10 +45,13 @@ FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ -!!! 提示 - 你也可以成為官方的 FastAPI 專家! +/// 提示 - 只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 +你也可以成為官方的 FastAPI 專家! + +只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 + +/// 你可以查看這些期間的 **FastAPI 專家**: diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index 2a1e1ed89..1fc634933 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -20,19 +20,23 @@ {!../../../docs_src/additional_responses/tutorial001.py!} ``` +/// note -!!! Note - 请记住,您必须直接返回 `JSONResponse` 。 +请记住,您必须直接返回 `JSONResponse` 。 -!!! Info - `model` 密钥不是OpenAPI的一部分。 - **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 - - 正确的位置是: - - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: - - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: - - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 - - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +/// +/// info + +`model` 密钥不是OpenAPI的一部分。 +**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 +- 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 + +/// **在OpenAPI中为该路径操作生成的响应将是:** @@ -163,12 +167,18 @@ {!../../../docs_src/additional_responses/tutorial002.py!} ``` -!!! Note - - 请注意,您必须直接使用 `FileResponse` 返回图像。 +/// note + +- 请注意,您必须直接使用 `FileResponse` 返回图像。 + +/// + +/// info + +- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 +- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 -!!! Info - - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 - - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 +/// ## 组合信息 您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。 diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index 54ec9775b..06320faad 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -18,17 +18,23 @@ {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "警告" - 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 +/// warning | "警告" - FastAPI 不会用模型等对该响应进行序列化。 +当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 - 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 +FastAPI 不会用模型等对该响应进行序列化。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。  +确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 - 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 +/// + +/// note | "技术细节" + +你也可以使用 `from starlette.responses import JSONResponse`。  + +出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 + +/// ## OpenAPI 和 API 文档 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index b2f6e3559..3d8afbb62 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -60,12 +60,14 @@ checker(q="somequery") {!../../../docs_src/dependencies/tutorial011.py!} ``` -!!! tip "提示" +/// tip | "提示" - 本章示例有些刻意,也看不出有什么用处。 +本章示例有些刻意,也看不出有什么用处。 - 这个简例只是为了说明高级依赖项的运作机制。 +这个简例只是为了说明高级依赖项的运作机制。 - 在有关安全的章节中,工具函数将以这种方式实现。 +在有关安全的章节中,工具函数将以这种方式实现。 - 只要能理解本章内容,就能理解安全工具背后的运行机制。 +只要能理解本章内容,就能理解安全工具背后的运行机制。 + +/// diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 17fc2830a..52f6acda1 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -37,9 +37,11 @@ browser --> proxy proxy --> server ``` -!!! tip "提示" +/// tip | "提示" - IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 +IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 + +/// API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如: @@ -76,11 +78,13 @@ $ uvicorn main:app --root-path /api/v1 Hypercorn 也支持 `--root-path `选项。 -!!! note "技术细节" +/// note | "技术细节" + +ASGI 规范定义的 `root_path` 就是为了这种用例。 - ASGI 规范定义的 `root_path` 就是为了这种用例。 +并且 `--root-path` 命令行选项支持 `root_path`。 - 并且 `--root-path` 命令行选项支持 `root_path`。 +/// ### 查看当前的 `root_path` @@ -168,9 +172,11 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶 这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 -!!! tip "提示" +/// tip | "提示" - 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 +使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 + +/// 接下来,创建 `routes.toml`: @@ -236,9 +242,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | "提示" + +注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 - 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 +/// 打开含 Traefik 端口的 URL,包含路径前缀:http://127.0.0.1:9999/api/v1/app。 @@ -281,9 +289,11 @@ $ uvicorn main:app --root-path /api/v1 ## 附加的服务器 -!!! warning "警告" +/// warning | "警告" - 此用例较难,可以跳过。 +此用例较难,可以跳过。 + +/// 默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。 @@ -322,17 +332,21 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | "提示" + +注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 - 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 +/// http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下: -!!! tip "提示" +/// tip | "提示" + +API 文档与所选的服务器进行交互。 - API 文档与所选的服务器进行交互。 +/// ### 从 `root_path` 禁用自动服务器 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 155ce2882..9594c72ac 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -!!! note "说明" - 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 +/// note | "说明" + +如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 + +/// ## 使用 `ORJSONResponse` @@ -25,17 +28,21 @@ {!../../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | "提示" + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 -!!! tip "小贴士" - `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 +/// +/// tip | "小贴士" +`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 + +/// ## HTML 响应 @@ -48,12 +55,15 @@ {!../../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | "提示" + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 + +/// ### 返回一个 `Response` @@ -65,11 +75,17 @@ {!../../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "警告" - *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 +/// warning | "警告" + +*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 + +/// + +/// info | "提示" -!!! info "提示" - 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 +当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 + +/// ### OpenAPI 中的文档和重载 `Response` @@ -99,10 +115,13 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import HTMLResponse`。 +/// note | "技术细节" + +你也可以使用 `from starlette.responses import HTMLResponse`。 + +**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 - **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 +/// ### `Response` @@ -151,15 +170,21 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。 -!!! warning "警告" - 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 +/// warning | "警告" + +在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 + +/// ```Python hl_lines="2 7" {!../../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "小贴士" - `ORJSONResponse` 可能是一个更快的选择。 +/// tip | "小贴士" + +`ORJSONResponse` 可能是一个更快的选择。 + +/// ### `RedirectResponse` @@ -187,8 +212,11 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 {!../../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "小贴士" - 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 +/// tip | "小贴士" + +注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 + +/// ### `FileResponse` diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index 5a93877cc..72567e245 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -20,13 +20,15 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 -!!! info "说明" +/// info | "说明" - 注意,数据类不支持 Pydantic 模型的所有功能。 +注意,数据类不支持 Pydantic 模型的所有功能。 - 因此,开发时仍需要使用 Pydantic 模型。 +因此,开发时仍需要使用 Pydantic 模型。 - 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 +但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +/// ## `response_model` 使用数据类 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index 8e5fa7d12..c9389f533 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -4,9 +4,11 @@ 事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 -!!! warning "警告" +/// warning | "警告" - **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 +**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 + +/// ## `startup` 事件 @@ -32,20 +34,26 @@ 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 -!!! info "说明" +/// info | "说明" + +`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 + +/// + +/// tip | "提示" - `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 +注意,本例使用 Python `open()` 标准函数与文件交互。 -!!! tip "提示" +这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 - 注意,本例使用 Python `open()` 标准函数与文件交互。 +但 `open()` 函数不支持使用 `async` 与 `await`。 - 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 +因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 - 但 `open()` 函数不支持使用 `async` 与 `await`。 +/// - 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 +/// info | "说明" -!!! info "说明" +有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 - 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 +/// diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index c4ffcb46c..56aad3bd2 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -16,17 +16,21 @@ 让我们从一个简单的 FastAPI 应用开始: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../../docs_src/generate_clients/tutorial001.py!} +``` - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +//// 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app -!!! tip - 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 +/// tip + +请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 + +/// 如果发送的数据字段不符,你也会看到编辑器的错误提示: @@ -128,17 +135,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### 生成带有标签的 TypeScript 客户端 @@ -185,17 +196,21 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +```Python hl_lines="6-7 10" +{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### 使用自定义操作ID生成TypeScript客户端 diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md index e39eed805..6525802fc 100644 --- a/docs/zh/docs/advanced/index.md +++ b/docs/zh/docs/advanced/index.md @@ -6,10 +6,13 @@ 你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 -!!! tip - 接下来的章节**并不一定是**「高级的」。 +/// tip - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节**并不一定是**「高级的」。 + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 06232fe17..764784ce3 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -43,11 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 -!!! note "技术细节" +/// note | "技术细节" - 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 +以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 - **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 +**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +/// ## `HTTPSRedirectMiddleware` diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index e2dadbfb0..7c7323cb5 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -35,9 +35,11 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" - `callback_url` 查询参数使用 Pydantic 的 URL 类型。 +`callback_url` 查询参数使用 Pydantic 的 URL 类型。 + +/// 此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 @@ -62,11 +64,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 本例没有实现回调本身(只是一行代码),只有文档部分。 -!!! tip "提示" +/// tip | "提示" + +实际的回调只是 HTTP 请求。 - 实际的回调只是 HTTP 请求。 +实现回调时,要使用 HTTPXRequests。 - 实现回调时,要使用 HTTPXRequests。 +/// ## 编写回调文档代码 @@ -76,11 +80,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 -!!! tip "提示" +/// tip | "提示" + +编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 - 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 +临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 - 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 +/// ### 创建回调的 `APIRouter` @@ -157,9 +163,11 @@ JSON 请求体包含如下内容: } ``` -!!! tip "提示" +/// tip | "提示" - 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 +注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +/// ### 添加回调路由 @@ -171,9 +179,11 @@ JSON 请求体包含如下内容: {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" + +注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 - 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 +/// ### 查看文档 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 7da9f251e..c37846916 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -2,8 +2,11 @@ ## OpenAPI 的 operationId -!!! warning - 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 +/// warning + +如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 + +/// 你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。 @@ -23,13 +26,19 @@ {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 +/// tip + +如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 + +/// + +/// warning + +如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 -!!! warning - 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 +即使它们在不同的模块中(Python 文件)。 - 即使它们在不同的模块中(Python 文件)。 +/// ## 从 OpenAPI 中排除 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 3e53c5319..dd942a981 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -28,20 +28,26 @@ {!../../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 +/// tip - 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 +需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 - 同时,你也应当仅反馈通过`response_model`过滤过的数据。 +所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 + +同时,你也应当仅反馈通过`response_model`过滤过的数据。 + +/// ### 更多信息 -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 +/// note | "技术细节" + +你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 + +为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 - 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 +因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 - 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 +/// 如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档 diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 797a878eb..b2c7de8fd 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -!!! tip "小贴士" - `JSONResponse` 本身是一个 `Response` 的子类。 +/// tip | "小贴士" + +`JSONResponse` 本身是一个 `Response` 的子类。 + +/// 当你返回一个 `Response` 时,**FastAPI** 会直接传递它。 @@ -36,10 +39,13 @@ {!../../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。 +/// note | "技术细节" + +你也可以使用 `from starlette.responses import JSONResponse`。 + +出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 - 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 +/// ## 返回自定义 `Response` diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index 229efffcb..e18d1620d 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -25,12 +25,15 @@ ``` -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 +/// note | "技术细节" - **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 +你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 - 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 +**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 + +由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 + +/// ## 自定义头部 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index ab8961e7c..a76353186 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -59,26 +68,36 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` + +//// - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` 这类似于: ```Python @@ -141,23 +160,32 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +//// diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index e2bef4765..836086ae2 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -4,10 +4,13 @@ 除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -!!! tip "小贴士" - 接下来的章节 **并不一定是 "高级的"**. +/// tip | "小贴士" - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节 **并不一定是 "高级的"**. + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index e5eeffb0a..b75ae11a4 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -10,19 +10,21 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证 本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 -!!! warning "警告" +/// warning | "警告" - 本章内容较难,刚接触 FastAPI 的新手可以跳过。 +本章内容较难,刚接触 FastAPI 的新手可以跳过。 - OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 +OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 - 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 +但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 - 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 +不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 - 很多情况下,OAuth2 作用域就像一把牛刀。 +很多情况下,OAuth2 作用域就像一把牛刀。 - 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 +但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +/// ## OAuth2 作用域与 OpenAPI @@ -44,15 +46,17 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | "说明" + +OAuth2 中,**作用域**只是声明特定权限的字符串。 - OAuth2 中,**作用域**只是声明特定权限的字符串。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +这些细节只是特定的实现方式。 - 这些细节只是特定的实现方式。 +对 OAuth2 来说,它们都只是字符串而已。 - 对 OAuth2 来说,它们都只是字符串而已。 +/// ## 全局纵览 @@ -90,11 +94,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 这样,返回的 JWT 令牌中就包含了作用域。 -!!! danger "危险" +/// danger | "危险" - 为了简明起见,本例把接收的作用域直接添加到了令牌里。 +为了简明起见,本例把接收的作用域直接添加到了令牌里。 - 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 +但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +/// ```Python hl_lines="153" {!../../../docs_src/security/tutorial005.py!} @@ -116,23 +122,27 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 本例要求使用作用域 `me`(还可以使用更多作用域)。 -!!! note "笔记" +/// note | "笔记" + +不必在不同位置添加不同的作用域。 - 不必在不同位置添加不同的作用域。 +本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 - 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 +/// ```Python hl_lines="4 139 166" {!../../../docs_src/security/tutorial005.py!} ``` -!!! info "技术细节" +/// info | "技术细节" - `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 +`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 - 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 +但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 - 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 +但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +/// ## 使用 `SecurityScopes` @@ -221,11 +231,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` -!!! tip "提示" +/// tip | "提示" + +此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 - 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 +所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 - 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 +/// ## `SecurityScopes` 的更多细节 @@ -263,11 +275,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 -!!! note "笔记" +/// note | "笔记" + +每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 - 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 +但归根结底,它们使用的都是 OAuth2 标准。 - 但归根结底,它们使用的都是 OAuth2 标准。 +/// **FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index d793b9c7f..37a2d98d3 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 环境变量 -!!! tip - 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 +/// tip + +如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 + +/// 环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。 您可以在 shell 中创建和使用环境变量,而无需使用 Python: -=== "Linux、macOS、Windows Bash" +//// tab | Linux、macOS、Windows Bash + +
+ +```console +// 您可以创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" -
+// 然后您可以与其他程序一起使用它,例如 +$ echo "Hello $MY_NAME" - ```console - // 您可以创建一个名为 MY_NAME 的环境变量 - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // 然后您可以与其他程序一起使用它,例如 - $ echo "Hello $MY_NAME" +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" - ```console - // 创建一个名为 MY_NAME 的环境变量 - $ $Env:MY_NAME = "Wade Wilson" +// 与其他程序一起使用它,例如 +$ echo "Hello $Env:MY_NAME" - // 与其他程序一起使用它,例如 - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### 在 Python 中读取环境变量 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - `os.getenv()` 的第二个参数是要返回的默认值。 +/// tip + +`os.getenv()` 的第二个参数是要返回的默认值。 - 如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 +如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 + +/// 然后,您可以调用该 Python 程序: @@ -116,8 +126,11 @@ Hello World from Python -!!! tip - 您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 +/// tip + +您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 + +/// ### 类型和验证 @@ -141,8 +154,11 @@ Hello World from Python {!../../../docs_src/settings/tutorial001.py!} ``` -!!! tip - 如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 +/// tip + +如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 + +/// 然后,当您创建该 `Settings` 类的实例(在此示例中是 `settings` 对象)时,Pydantic 将以不区分大小写的方式读取环境变量,因此,大写的变量 `APP_NAME` 仍将为属性 `app_name` 读取。 @@ -170,8 +186,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app -!!! tip - 要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 +/// tip + +要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 + +/// 然后,`admin_email` 设置将为 `"deadpool@example.com"`。 @@ -194,8 +213,12 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app ```Python hl_lines="3 11-13" {!../../../docs_src/settings/app01/main.py!} ``` -!!! tip - 您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// tip + +您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// ## 在依赖项中使用设置 @@ -217,54 +240,75 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ 非注解版本 - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ 非注解版本" +如果可能,请尽量使用 `Annotated` 版本。 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// + +```Python hl_lines="5 11-12" +{!> ../../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// -!!! tip - 我们稍后会讨论 `@lru_cache`。 +/// tip - 目前,您可以将 `get_settings()` 视为普通函数。 +我们稍后会讨论 `@lru_cache`。 + +目前,您可以将 `get_settings()` 视为普通函数。 + +/// 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 19-21" +{!> ../../../docs_src/settings/app02_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="16 18-20" +{!> ../../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// ### 设置和测试 @@ -284,15 +328,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 这种做法相当常见,有一个名称,这些环境变量通常放在一个名为 `.env` 的文件中,该文件被称为“dotenv”。 -!!! tip - 以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 +/// tip - 但是,dotenv 文件实际上不一定要具有确切的文件名。 +以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 + +但是,dotenv 文件实际上不一定要具有确切的文件名。 + +/// Pydantic 支持使用外部库从这些类型的文件中读取。您可以在Pydantic 设置: Dotenv (.env) 支持中阅读更多相关信息。 -!!! tip - 要使其工作,您需要执行 `pip install python-dotenv`。 +/// tip + +要使其工作,您需要执行 `pip install python-dotenv`。 + +/// ### `.env` 文件 @@ -313,8 +363,11 @@ APP_NAME="ChimichangApp" 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 -!!! tip - `Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 +/// tip + +`Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 + +/// ### 使用 `lru_cache` 仅创建一次 `Settings` @@ -339,26 +392,35 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../../docs_src/settings/app03_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="1 10" +{!> ../../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 612b69176..b09644e39 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -31,20 +31,26 @@ $ pip install jinja2 {!../../../docs_src/templates/tutorial001.py!} ``` -!!! note "笔记" +/// note | "笔记" - 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 - 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 +在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 +并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 -!!! tip "提示" +/// - 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 +/// tip | "提示" -!!! note "技术细节" +通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 - 您还可以使用 `from starlette.templating import Jinja2Templates`。 +/// - **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 +/// note | "技术细节" + +您还可以使用 `from starlette.templating import Jinja2Templates`。 + +**FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 + +/// ## 编写模板 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md index 8dc95c25f..58bf9af8c 100644 --- a/docs/zh/docs/advanced/testing-database.md +++ b/docs/zh/docs/advanced/testing-database.md @@ -52,11 +52,13 @@ {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip "提示" +/// tip | "提示" - 为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 +为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 - 为了把注意力集中在测试代码上,本例只是复制了这段代码。 +为了把注意力集中在测试代码上,本例只是复制了这段代码。 + +/// ## 创建数据库 @@ -82,9 +84,11 @@ Base.metadata.create_all(bind=engine) {!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` -!!! tip "提示" +/// tip | "提示" + +`overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 - `overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 +/// ## 测试应用 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index 487f5ebf5..cc9a38200 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -32,13 +32,15 @@ {!../../../docs_src/dependency_testing/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" - **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 +**FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 - 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 +原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 - FastAPI 可以覆盖这些位置的依赖项。 +FastAPI 可以覆盖这些位置的依赖项。 + +/// 然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: @@ -46,6 +48,8 @@ app.dependency_overrides = {} ``` -!!! tip "提示" +/// tip | "提示" + +如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 - 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 +/// diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index f303e1d67..795b73945 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -8,6 +8,8 @@ {!../../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "笔记" +/// note | "笔记" - 更多细节详见 Starlette 官档 - 测试 WebSockets。 +更多细节详见 Starlette 官档 - 测试 WebSockets。 + +/// diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index 1842c2e27..bc9e898d9 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -35,20 +35,24 @@ 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 -!!! tip "提示" +/// tip | "提示" - 注意,本例除了声明请求参数之外,还声明了路径参数。 +注意,本例除了声明请求参数之外,还声明了路径参数。 - 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 +因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 - 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 +同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +/// ## `Request` 文档 更多细节详见 Starlette 官档 - `Request` 对象。 -!!! note "技术细节" +/// note | "技术细节" + +您也可以使用 `from starlette.requests import Request`。 - 您也可以使用 `from starlette.requests import Request`。 +**FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 - **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 +/// diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index a5cbdd965..3fcc36dfe 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -46,10 +46,13 @@ $ pip install websockets {!../../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技术细节" - 您也可以使用 `from starlette.websockets import WebSocket`。 +/// note | "技术细节" - **FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 +您也可以使用 `from starlette.websockets import WebSocket`。 + +**FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 + +/// ## 等待消息并发送消息 @@ -106,46 +109,65 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ 非带注解版本 -=== "Python 3.9+" +/// tip - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ 非带注解版本" +//// tab | Python 3.8+ 非带注解版本 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// tip - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+ 非带注解版本" +/// + +```Python hl_lines="68-69 81" +{!> ../../../docs_src/websockets/tutorial002.py!} +``` - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 +由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 - 您可以使用规范中定义的有效代码。 +您可以使用规范中定义的有效代码。 + +/// ### 尝试带有依赖项的 WebSockets @@ -164,8 +186,11 @@ $ uvicorn main:app --reload * "Item ID",用于路径。 * "Token",作为查询参数。 -!!! tip - 注意,查询参数 `token` 将由依赖项处理。 +/// tip + +注意,查询参数 `token` 将由依赖项处理。 + +/// 通过这样,您可以连接 WebSocket,然后发送和接收消息: @@ -175,17 +200,21 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// 尝试以下操作: @@ -199,12 +228,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 +/// tip + +上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 + +但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 - 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 +如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 - 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 +/// ## 更多信息 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index b34ef63e0..822ceeee4 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 你只能在被 `async def` 创建的函数内使用 `await` +/// note + +你只能在被 `async def` 创建的函数内使用 `await` + +/// --- @@ -136,8 +139,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -392,12 +401,15 @@ Starlette (和 **FastAPI**) 是基于 +
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+ -=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// + +//// tab | Windows Bash - Or if you use Bash for Windows (e.g.
Git Bash): +Or if you use Bash for Windows (e.g. Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// 要检查操作是否成功,运行: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` -
+
+ +//// 如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip - 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 +/// tip + +每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - 这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 +这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 + +/// ### pip @@ -125,10 +138,13 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 -!!! note "技术细节" - 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 +/// note | "技术细节" + +仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 - 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 +这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 + +/// ### 格式化 @@ -170,20 +186,23 @@ $ python ./scripts/docs.py live 这样,你可以编辑文档 / 源文件并实时查看更改。 -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip - 进入语言目录,如果是英文文档,目录则是 `docs/en/`: +或者你也可以手动执行和该脚本一样的操作 - ```console - $ cd docs/en/ - ``` +进入语言目录,如果是英文文档,目录则是 `docs/en/`: - 在该目录执行 `mkdocs` 命令 +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +在该目录执行 `mkdocs` 命令 + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer CLI (可选) @@ -210,8 +229,11 @@ Completion will take effect once you restart the terminal. 在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 -!!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 +/// tip + +你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 + +/// 所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 @@ -256,10 +278,13 @@ $ uvicorn tutorial001:app --reload * 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 -!!! tip - 你可以为已有的 pull requests 添加包含修改建议的评论。 +/// tip + +你可以为已有的 pull requests 添加包含修改建议的评论。 + +详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 - 详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 +/// * 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 @@ -283,8 +308,11 @@ $ uvicorn tutorial001:app --reload 对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 -!!! tip - 默认语言是英语,位于 `docs/en/`目录。 +/// tip + +默认语言是英语,位于 `docs/en/`目录。 + +/// 现在为西班牙语文档运行实时服务器: @@ -301,20 +329,23 @@ $ python ./scripts/docs.py live es -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip + +或者你也可以手动执行和该脚本一样的操作 - 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: +进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +在该目录执行 `mkdocs` 命令 - 在该目录执行 `mkdocs` 命令 +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// 现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 @@ -334,8 +365,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 +/// tip + +注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 + +/// 回到浏览器你就可以看到刚刚更新的章节了。🎉 @@ -370,8 +404,11 @@ Successfully initialized: docs/ht INHERIT: ../en/mkdocs.yml ``` -!!! tip - 你也可以自己手动创建包含这些内容的文件。 +/// tip + +你也可以自己手动创建包含这些内容的文件。 + +/// 这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md index 86d995b75..7a0b6c3d2 100644 --- a/docs/zh/docs/deployment/concepts.md +++ b/docs/zh/docs/deployment/concepts.md @@ -154,11 +154,13 @@ 但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...... -!!! tip +/// tip - ...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 +...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 - 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + +/// 您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。 @@ -245,11 +247,13 @@ -!!! tip +/// tip + +如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 - 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// ## 启动之前的步骤 @@ -265,12 +269,13 @@ 当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。 -!!! tip +/// tip - 另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 +另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 - 在这种情况下,您就不必担心这些。 🤷 + 在这种情况下,您就不必担心这些。 🤷 +/// ### 前面步骤策略的示例 @@ -282,9 +287,11 @@ * 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序 * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。 -!!! tip +/// tip + +我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// ## 资源利用率 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index 782c6d578..e5f66dba1 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -4,9 +4,11 @@ 使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 -!!! tip - 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 +/// tip +赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 + +///
Dockerfile Preview 👀 @@ -137,10 +139,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - 还有其他文件格式和工具来定义和安装依赖项。 +/// info + +还有其他文件格式和工具来定义和安装依赖项。 + + 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 - 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 +/// ### 创建 **FastAPI** 代码 @@ -232,8 +237,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。 -!!! tip - 通过单击代码中的每个数字气泡来查看每行的作用。 👆 +/// tip + +通过单击代码中的每个数字气泡来查看每行的作用。 👆 + +/// 你现在应该具有如下目录结构: ``` @@ -306,10 +314,13 @@ $ docker build -t myimage . -!!! tip - 注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 +/// tip - 在本例中,它是相同的当前目录(`.`)。 +注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 + +在本例中,它是相同的当前目录(`.`)。 + +/// ### 启动 Docker 容器 @@ -409,8 +420,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它可以是另一个容器,例如使用 Traefik,处理 **HTTPS** 和 **自动**获取**证书**。 -!!! tip - Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 +/// tip + +Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 + +/// 或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。 @@ -439,8 +453,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。 -!!! tip - 用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 +/// tip + +用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 + +/// 当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。 @@ -526,8 +543,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。 -!!! info - 如果你使用 Kubernetes,这可能是 Init Container。 +/// info + +如果你使用 Kubernetes,这可能是 Init Container。 + +/// 如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。 @@ -546,8 +566,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - 你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 +/// warning + +你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +/// 该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。 @@ -555,8 +578,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它还支持通过一个脚本运行**开始前的先前步骤** 。 -!!! tip - 要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 +/// tip + +要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 + +/// ### 官方 Docker 镜像上的进程数 @@ -686,8 +712,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。 -!!! tip - 单击气泡数字可查看每行的作用。 +/// tip + +单击气泡数字可查看每行的作用。 + +/// **Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index cf01a4585..e5d66482a 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -69,8 +69,11 @@ 这个操作一般只需要在最开始执行一次。 -!!! tip - 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 +/// tip + +域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +/// ### DNS @@ -116,8 +119,11 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 -!!! tip - 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 +/// tip + +请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +/// ### HTTPS 请求 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index ca7142613..30ee7a1e9 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -23,77 +23,89 @@ 您可以使用以下命令安装 ASGI 兼容服务器: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 +* Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 -
+
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` - ```console - $ pip install "uvicorn[standard]" +
+ +/// tip - ---> 100% - ``` +通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 -
+其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 - !!! tip - 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 +/// - 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 +//// -=== "Hypercorn" +//// tab | Hypercorn - * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 +* Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 -
+
- ```console - $ pip install hypercorn +```console +$ pip install hypercorn - ---> 100% - ``` +---> 100% +``` -
+
- ...或任何其他 ASGI 服务器。 +...或任何其他 ASGI 服务器。 +//// ## 运行服务器程序 您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
+```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` -
+
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+如果您正在使用`--reload`选项,请记住删除它。 -!!! warning - 如果您正在使用`--reload`选项,请记住删除它。 + `--reload` 选项消耗更多资源,并且更不稳定。 - `--reload` 选项消耗更多资源,并且更不稳定。 + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 - 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 +/// ## Hypercorn with Trio diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md index 330ddb3d7..eb0252a5c 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -17,12 +17,13 @@ 在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 -!!! info - 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +/// info - 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +/// ## Gunicorn with Uvicorn Workers diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md index 75b870139..228bb0765 100644 --- a/docs/zh/docs/deployment/versions.md +++ b/docs/zh/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。 -!!! tip - "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 +/// tip + +"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 + +/// 因此,你应该能够固定到如下版本: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 "MINOR"版本中会添加breaking changes和新功能。 -!!! tip - "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 +/// tip + +"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 + +/// ## 升级FastAPI版本 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index dd3914921..00235bd02 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -80,5 +80,8 @@ FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变 在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 -!!! tip "提示" - 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 +/// tip | "提示" + +你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 + +/// diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md index 87e6c8e6b..30a75240c 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -45,10 +45,13 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ -!!! 小提示 - 你也可以成为认可的 FastAPI 专家! +/// 小提示 - 只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 +你也可以成为认可的 FastAPI 专家! + +只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 + +/// 你可以查看不同时期的 **FastAPI 专家**: diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index d8190032f..24dc3e8ce 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -65,10 +65,13 @@ my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` 意思是: +/// info - 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` 意思是: + +直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 编辑器支持 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index e3aa5575c..fc47ed89d 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -108,11 +108,13 @@ 快加入 👥 Discord 聊天服务器 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -!!! tip "提示" +/// tip | "提示" - 如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 +如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 - 聊天室仅供闲聊。 +聊天室仅供闲聊。 + +/// ### 别在聊天室里提问 diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md index c0688c72a..262dcfaee 100644 --- a/docs/zh/docs/how-to/index.md +++ b/docs/zh/docs/how-to/index.md @@ -6,6 +6,8 @@ 如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 -!!! 小技巧 +/// 小技巧 - 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 +如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 + +/// diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 214b47611..c78852539 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -12,8 +12,11 @@ 但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。 -!!! note - 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 +/// note + +如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 + +/// ## 动机 @@ -253,8 +256,11 @@ John Doe {!../../../docs_src/python_types/tutorial010.py!} ``` -!!! info - 想进一步了解 Pydantic,请阅读其文档. +/// info + +想进一步了解 Pydantic,请阅读其文档. + +/// 整个 **FastAPI** 建立在 Pydantic 的基础之上。 @@ -282,5 +288,8 @@ John Doe 最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。 -!!! info - 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 +/// info + +如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 + +/// diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 94b75d4fd..95fd7b6b5 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -57,41 +57,57 @@ **FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="14 16 23 26" +{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ 没Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.10+ 没Annotated" +/// + +```Python hl_lines="11 13 20 23" +{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ 没Annotated -=== "Python 3.8+ 没Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="13 15 22 25" +{!> ../../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// 该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 422cd7c16..a0c7095e9 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。 -!!! info - 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 +/// info + +如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 + +/// ## 一个文件结构示例 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 +/// tip + +上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 - 这就是能将代码从一个文件导入到另一个文件的原因。 +这就是能将代码从一个文件导入到另一个文件的原因。 - 例如,在 `app/main.py` 中,你可以有如下一行: +例如,在 `app/main.py` 中,你可以有如下一行: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。 * 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。 @@ -99,8 +105,11 @@ 所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。 -!!! tip - 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 +/// tip + +在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 + +/// 我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。 @@ -116,10 +125,13 @@ {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 我们正在使用虚构的请求首部来简化此示例。 +/// tip + +我们正在使用虚构的请求首部来简化此示例。 + +但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 - 但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 +/// ## 其他使用 `APIRouter` 的模块 @@ -163,8 +175,11 @@ async def read_item(item_id: str): 我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。 -!!! tip - 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 +/// tip + +请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 + +/// 最终结果是项目相关的路径现在为: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。 * 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。 -!!! tip - 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 +/// tip + +在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 + +/// + +/// check -!!! check - `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 +`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 + +/// ### 导入依赖项 @@ -201,8 +222,11 @@ async def read_item(item_id: str): #### 相对导入如何工作 -!!! tip - 如果你完全了解导入的工作原理,请从下面的下一部分继续。 +/// tip + +如果你完全了解导入的工作原理,请从下面的下一部分继续。 + +/// 一个单点 `.`,例如: @@ -269,10 +293,13 @@ from ...dependencies import get_token_header {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 最后的这个路径操作将包含标签的组合:`["items","custom"]`。 +/// tip + +最后的这个路径操作将包含标签的组合:`["items","custom"]`。 - 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 +并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 + +/// ## `FastAPI` 主体 @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 第一个版本是「相对导入」: +/// info + +第一个版本是「相对导入」: - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 第二个版本是「绝对导入」: +第二个版本是「绝对导入」: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 - 要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 +/// ### 避免名称冲突 @@ -372,26 +402,35 @@ from .routers.users import router {!../../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 +/// info - `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 +`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 + +`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 + +/// 使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。 它将包含来自该路由器的所有路由作为其一部分。 -!!! note "技术细节" - 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 +/// note | "技术细节" + +实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 + +所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 + +/// - 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 +/// check -!!! check - 包含路由器时,你不必担心性能问题。 +包含路由器时,你不必担心性能问题。 - 这将花费几微秒时间,并且只会在启动时发生。 +这将花费几微秒时间,并且只会在启动时发生。 - 因此,它不会影响性能。⚡ +因此,它不会影响性能。⚡ + +/// ### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter` @@ -438,16 +477,19 @@ from .routers.users import router 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -!!! info "特别的技术细节" - **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 +/// info | "特别的技术细节" + +**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 + +--- - --- +`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 - `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 +这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 - 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 +由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 - 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 +/// ## 查看自动化的 API 文档 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 6c68f1008..6e4c385dd 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,101 +6,139 @@ 首先,从 Pydantic 中导入 `Field`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -!!! warning "警告" +/// - 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 +```Python hl_lines="2" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="4" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | "警告" + +注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 + +/// ## 声明模型属性 然后,使用 `Field` 定义模型的属性: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="12-15" +{!> ../../../docs_src/body_fields/tutorial001_an.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +/// + +```Python hl_lines="9-12" +{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11-14" +{!> ../../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -!!! note "技术细节" +/// note | "技术细节" + +实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 + +Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 - 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 +`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 - Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 +注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 - `Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 +/// tip | "提示" -!!! tip "提示" +注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 - 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 +/// ## 添加更多信息 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c93ef2f5c..fe951e544 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-20" +{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-19" +{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// + +```Python hl_lines="19-21" +{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 -!!! note - 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 +/// ## 多个请求体参数 @@ -62,17 +81,21 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -93,9 +116,11 @@ } ``` -!!! note - 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 +/// note +请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 + +/// **FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。 @@ -112,41 +137,57 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="22" +{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -181,45 +222,63 @@ q: str = None 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.9+" +/// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +```Python hl_lines="25" +{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="27" +{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +/// info -!!! info - `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +/// ## 嵌入单个请求体参数 @@ -235,41 +294,57 @@ item: Item = Body(embed=True) 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="17" +{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 3f519ae33..26837abc6 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -51,23 +55,29 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial002.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// ## Set 类型 @@ -77,23 +87,29 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +```Python hl_lines="1 14" +{!> ../../../docs_src/body_nested_models/tutorial003.py!} +``` + +//// 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -115,45 +131,57 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -186,23 +214,29 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="2 8" +{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 10" +{!> ../../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -210,23 +244,29 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -254,33 +294,45 @@ Pydantic 模型的每个属性都具有类型。 } ``` -!!! info - 请注意 `images` 键现在具有一组 image 对象是如何发生的。 +/// info + +请注意 `images` 键现在具有一组 image 对象是如何发生的。 + +/// ## 深度嵌套模型 你可以定义任意深度的嵌套模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 -!!! info - 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 +/// ## 纯列表请求体 @@ -292,17 +344,21 @@ images: List[Image] 例如: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## 无处不在的编辑器支持 @@ -332,26 +388,33 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +请记住 JSON 仅支持将 `str` 作为键。 -!!! tip - 请记住 JSON 仅支持将 `str` 作为键。 +但是 Pydantic 具有自动转换数据的功能。 - 但是 Pydantic 具有自动转换数据的功能。 +这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 - 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 +然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 - 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 +/// ## 总结 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index e529fc914..6c74d12e0 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -34,15 +34,17 @@ 即,只发送要更新的数据,其余数据保持不变。 -!!! note "笔记" +/// note | "笔记" - `PATCH` 没有 `PUT` 知名,也怎么不常用。 +`PATCH` 没有 `PUT` 知名,也怎么不常用。 - 很多人甚至只用 `PUT` 实现部分更新。 +很多人甚至只用 `PUT` 实现部分更新。 - **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 +**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 - 但本指南也会分别介绍这两种操作各自的用途。 +但本指南也会分别介绍这两种操作各自的用途。 + +/// ### 使用 Pydantic 的 `exclude_unset` 参数 @@ -87,15 +89,19 @@ {!../../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "提示" +/// tip | "提示" + +实际上,HTTP `PUT` 也可以完成相同的操作。 +但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 + +/// - 实际上,HTTP `PUT` 也可以完成相同的操作。 - 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 +/// note | "笔记" -!!! note "笔记" +注意,输入模型仍需验证。 - 注意,输入模型仍需验证。 +因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 - 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 +为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 - 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 +/// diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 65d459cd1..c47abec77 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -8,29 +8,35 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 -!!! info "说明" +/// info | "说明" - 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 +发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 - 规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 +规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 - 我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 +我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 + +/// ## 导入 Pydantic 的 `BaseModel` 从 `pydantic` 中导入 `BaseModel`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="4" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ## 创建数据模型 @@ -38,17 +44,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="5-9" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="7-11" +{!> ../../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -76,17 +86,21 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial001.py!} +``` + +//// ……此处,请求体参数的类型为 `Item` 模型。 @@ -135,33 +149,39 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 -!!! tip "提示" +/// tip | "提示" + +使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 - 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 +该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: - 该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: +* 自动补全 +* 类型检查 +* 代码重构 +* 查找 +* 代码审查 - * 自动补全 - * 类型检查 - * 代码重构 - * 查找 - * 代码审查 +/// ## 使用模型 在*路径操作*函数内部直接访问模型对象的属性: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/body/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## 请求体 + 路径参数 @@ -169,17 +189,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../../docs_src/body/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../../docs_src/body/tutorial003.py!} +``` + +//// ## 请求体 + 路径参数 + 查询参数 @@ -187,17 +211,21 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../../docs_src/body/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18" +{!> ../../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// 函数参数按如下规则进行识别: @@ -205,11 +233,13 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 - 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 - 类型是 **Pydantic 模型**的参数,是**请求体** -!!! note "笔记" +/// note | "笔记" + +因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 - 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 +FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 - FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 +/// ## 不使用 Pydantic diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 8571422dd..7ca77696e 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 首先,导入 `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## 声明 `Cookie` 参数 @@ -49,51 +65,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note | "技术细节" - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 -!!! note "技术细节" +注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 - `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 +/// info | "说明" -!!! info "说明" +必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 - 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index ddd4e7682..de880f347 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -78,7 +78,10 @@ 更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 -!!! note "技术细节" - 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 +/// note | "技术细节" - 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 +你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 + +出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 + +/// diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 51801d498..945094207 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -70,8 +70,11 @@ from myapp import app uvicorn.run(app, host="0.0.0.0", port=8000) ``` -!!! info - 更多信息请检查 Python 官方文档. +/// info + +更多信息请检查 Python 官方文档. + +/// ## 使用你的调试器运行代码 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 1866da298..9932f90fc 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="9-13" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="11-15" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// 注意用于创建类实例的 `__init__` 方法: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="12" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...它与我们以前的 `common_parameters` 具有相同的参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6" +{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="9" +{!> ../../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ..就像: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial003.py!} +``` + +//// 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +```Python hl_lines="19" +{!> ../../../docs_src/dependencies/tutorial004.py!} +``` + +//// ... **FastAPI** 会知道怎么处理。 -!!! tip - 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 +/// tip + +如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 + +这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 - 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 61ea371e5..e6bbd47c1 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,19 +20,23 @@ 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -!!! tip "提示" +/// tip | "提示" - 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 +有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 - 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 +在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 - 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 +使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 -!!! info "说明" +/// - 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 +/// info | "说明" - 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 +本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 + +但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 + +/// ## 依赖项错误和返回值 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 4159d626e..beca95d45 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,20 +4,24 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17-18 25-26" +{!> ../../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 如果可能,请尽量使用“ Annotated”版本。 +如果可能,请尽量使用“ Annotated”版本。 - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +/// + +```Python hl_lines="16-17 24-25" +{!> ../../../docs_src/dependencies/tutorial008.py!} +``` + +//// 同样,你可以有混合了`yield`和`return`的依赖。 @@ -124,12 +148,13 @@ FastAPI支持在完成后执行一些创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 @@ -242,12 +278,15 @@ with open("./somefile.txt") as f: {!../../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - 另一种创建上下文管理器的方法是: +/// tip + +另一种创建上下文管理器的方法是: + +* `@contextlib.contextmanager`或者 +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager`或者 - * `@contextlib.asynccontextmanager` +使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 - 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 - 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md index 7a133061d..b360bf71e 100644 --- a/docs/zh/docs/tutorial/dependencies/index.md +++ b/docs/zh/docs/tutorial/dependencies/index.md @@ -75,9 +75,11 @@ FastAPI 提供了简单易用,但功能强大的** read_users 这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。 -!!! check "检查" +/// check | "检查" + +注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 - 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 +只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 - 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 +/// ## 要不要使用 `async`? @@ -114,9 +118,11 @@ common_parameters --> read_users 上述这些操作都是可行的,**FastAPI** 知道该怎么处理。 -!!! note "笔记" +/// note | "笔记" + +如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 - 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 +/// ## 与 OpenAPI 集成 diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md index 58377bbfe..d2a204c3d 100644 --- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md @@ -41,11 +41,13 @@ FastAPI 支持创建含**子依赖项**的依赖项。 {!../../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "信息" +/// info | "信息" - 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 +注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 - 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 +但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 + +/// ```mermaid graph TB @@ -79,10 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False 但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。 -!!! tip "提示" +/// tip | "提示" + +这些简单的例子现在看上去虽然没有什么实用价值, - 这些简单的例子现在看上去虽然没有什么实用价值, +但在**安全**一章中,您会了解到这些例子的用途, - 但在**安全**一章中,您会了解到这些例子的用途, +以及这些例子所能节省的代码量。 - 以及这些例子所能节省的代码量。 +/// diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 859ebc2e8..8270a4093 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ 它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../../docs_src/encoder/tutorial001.py!} +``` + +//// 在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 @@ -38,5 +42,8 @@ 这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 -!!! note - `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 +/// note + +`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 + +/// diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index cf39de0dd..3b50da01f 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="1 3 13-17" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// 注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="18-19" +{!> ../../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 94d82c524..b23d4188f 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -8,27 +8,33 @@ * **输出模型**不应含密码 * **数据库模型**需要加密的密码 -!!! danger "危险" +/// danger | "危险" - 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 +千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 - 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 +如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 + +/// ## 多个模型 下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// ### `**user_in.dict()` 简介 @@ -140,9 +146,11 @@ UserInDB( ) ``` -!!! warning "警告" +/// warning | "警告" + +辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 - 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 +/// ## 减少重复 @@ -162,17 +170,21 @@ FastAPI 可以做得更好。 通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` 或者 `anyOf` @@ -182,21 +194,27 @@ FastAPI 可以做得更好。 为此,请使用 Python 标准类型提示 `typing.Union`: -!!! note "笔记" +/// note | "笔记" + +定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 - 定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../../docs_src/extra_models/tutorial003.py!} +``` + +//// ## 模型列表 @@ -204,17 +222,21 @@ FastAPI 可以做得更好。 为此,请使用标准的 Python `typing.List`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## 任意 `dict` 构成的响应 @@ -224,17 +246,21 @@ FastAPI 可以做得更好。 此时,可以使用 `typing.Dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 30fae99cf..779d1b8be 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -24,13 +24,15 @@ $ uvicorn main:app --reload -!!! note - `uvicorn main:app` 命令含义如下: +/// note - * `main`:`main.py` 文件(一个 Python「模块」)。 - * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 - * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 +`uvicorn main:app` 命令含义如下: +* `main`:`main.py` 文件(一个 Python「模块」)。 +* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 +* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 + +/// 在输出中,会有一行信息像下面这样: @@ -138,10 +140,13 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 `FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。 -!!! note "技术细节" - `FastAPI` 是直接从 `Starlette` 继承的类。 +/// note | "技术细节" + +`FastAPI` 是直接从 `Starlette` 继承的类。 + +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 - 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +/// ### 步骤 2:创建一个 `FastAPI`「实例」 @@ -201,8 +206,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - 「路径」也通常被称为「端点」或「路由」。 +/// info + +「路径」也通常被称为「端点」或「路由」。 + +/// 开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。 @@ -252,16 +260,19 @@ https://example.com/items/foo * 请求路径为 `/` * 使用 get 操作 -!!! info "`@decorator` Info" - `@something` 语法在 Python 中被称为「装饰器」。 +/// info | "`@decorator` Info" + +`@something` 语法在 Python 中被称为「装饰器」。 - 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 +像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 - 装饰器接收位于其下方的函数并且用它完成一些工作。 +装饰器接收位于其下方的函数并且用它完成一些工作。 - 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 +在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 - 它是一个「**路径操作装饰器**」。 +它是一个「**路径操作装饰器**」。 + +/// 你也可以使用其他的操作: @@ -276,14 +287,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 您可以随意使用任何一个操作(HTTP方法)。 +/// tip + +您可以随意使用任何一个操作(HTTP方法)。 + +**FastAPI** 没有强制要求操作有任何特定的含义。 - **FastAPI** 没有强制要求操作有任何特定的含义。 +此处提供的信息仅作为指导,而不是要求。 - 此处提供的信息仅作为指导,而不是要求。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 - 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +/// ### 步骤 4:定义**路径操作函数** @@ -311,8 +325,11 @@ https://example.com/items/foo {!../../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 +/// note + +如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 + +/// ### 步骤 5:返回内容 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 701cd241e..b5c027d44 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -67,14 +67,15 @@ ``` -!!! tip "提示" +/// tip | "提示" - 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 +触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 - 还支持传递 `dict`、`list` 等数据结构。 +还支持传递 `dict`、`list` 等数据结构。 - **FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +**FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +/// ## 添加自定义响应头 @@ -115,12 +116,13 @@ ``` -!!! note "技术细节" +/// note | "技术细节" - `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 +`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +/// ## 覆盖默认异常处理器 @@ -174,10 +176,11 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "警告" +/// warning | "警告" - 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +/// `RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 @@ -200,12 +203,13 @@ path -> item_id ``` -!!! note "技术细节" +/// note | "技术细节" - 还可以使用 `from starlette.responses import PlainTextResponse`。 +还可以使用 `from starlette.responses import PlainTextResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +/// ### 使用 `RequestValidationError` 的请求体 diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 25dfeba87..a9064c519 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ 首先,导入 `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// ## 声明 `Header` 参数 @@ -48,51 +64,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated -!!! note "技术细节" +/// tip - `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 +尽可能选择使用 `Annotated` 的版本。 - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial001.py!} +``` -!!! info "说明" +//// - 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 +/// note | "技术细节" + +`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 + +/// + +/// info | "说明" + +必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 + +/// ## 自动转换 @@ -110,46 +146,63 @@ 如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../../docs_src/header_params/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial002.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +//// -!!! warning "警告" +/// warning | "警告" - 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +/// ## 重复的请求头 @@ -161,50 +214,71 @@ 例如,声明 `X-Token` 多次出现的请求头,可以写成这样: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../../docs_src/header_params/tutorial003_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../../docs_src/header_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// 与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 6180d3de3..ab19f02c5 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。 -!!! note - 你也可以分开来安装。 +/// note - 假如你想将应用程序部署到生产环境,你可能要执行以下操作: +你也可以分开来安装。 - ``` - pip install fastapi - ``` +假如你想将应用程序部署到生产环境,你可能要执行以下操作: - 并且安装`uvicorn`来作为服务器: +``` +pip install fastapi +``` + +并且安装`uvicorn`来作为服务器: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +然后对你想使用的每个可选依赖项也执行相同的操作。 - 然后对你想使用的每个可选依赖项也执行相同的操作。 +/// ## 进阶用户指南 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 59a4af86e..3316e2ce4 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,101 +1,110 @@ -# 元数据和文档 URL - -你可以在 FastAPI 应用程序中自定义多个元数据配置。 - -## API 元数据 - -你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: - -| 参数 | 类型 | 描述 | -|------------|------|-------------| -| `title` | `str` | API 的标题。 | -| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | -| `description` | `str` | API 的简短描述。可以使用Markdown。 | -| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | -| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | -| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| -| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| - -你可以按如下方式设置它们: - -```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} -``` - -!!! tip - 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 - -通过这样设置,自动 API 文档看起来会像: - - - -## 标签元数据 - -### 创建标签元数据 - -让我们在带有标签的示例中为 `users` 和 `items` 试一下。 - -创建标签元数据并把它传递给 `openapi_tags` 参数: - -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 - -!!! tip "提示" - 不必为你使用的所有标签都添加元数据。 - -### 使用你的标签 - -将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: - -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -!!! info "信息" - 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 - -### 查看文档 - -如果你现在查看文档,它们会显示所有附加的元数据: - - - -### 标签顺序 - -每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 - -例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 - -## OpenAPI URL - -默认情况下,OpenAPI 模式服务于 `/openapi.json`。 - -但是你可以通过参数 `openapi_url` 对其进行配置。 - -例如,将其设置为服务于 `/api/v1/openapi.json`: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` - -如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 - -## 文档 URLs - -你可以配置两个文档用户界面,包括: - -* **Swagger UI**:服务于 `/docs`。 - * 可以使用参数 `docs_url` 设置它的 URL。 - * 可以通过设置 `docs_url=None` 禁用它。 -* ReDoc:服务于 `/redoc`。 - * 可以使用参数 `redoc_url` 设置它的 URL。 - * 可以通过设置 `redoc_url=None` 禁用它。 - -例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +# 元数据和文档 URL + +你可以在 FastAPI 应用程序中自定义多个元数据配置。 + +## API 元数据 + +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: + +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| + +你可以按如下方式设置它们: + +```Python hl_lines="4-6" +{!../../../docs_src/metadata/tutorial001.py!} +``` + +/// tip + +您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + +/// + +通过这样设置,自动 API 文档看起来会像: + + + +## 标签元数据 + +### 创建标签元数据 + +让我们在带有标签的示例中为 `users` 和 `items` 试一下。 + +创建标签元数据并把它传递给 `openapi_tags` 参数: + +```Python hl_lines="3-16 18" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 + +/// tip | "提示" + +不必为你使用的所有标签都添加元数据。 + +/// + +### 使用你的标签 + +将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: + +```Python hl_lines="21 26" +{!../../../docs_src/metadata/tutorial004.py!} +``` + +/// info | "信息" + +阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 + +/// + +### 查看文档 + +如果你现在查看文档,它们会显示所有附加的元数据: + + + +### 标签顺序 + +每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 + +例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 + +## OpenAPI URL + +默认情况下,OpenAPI 模式服务于 `/openapi.json`。 + +但是你可以通过参数 `openapi_url` 对其进行配置。 + +例如,将其设置为服务于 `/api/v1/openapi.json`: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial002.py!} +``` + +如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 + +## 文档 URLs + +你可以配置两个文档用户界面,包括: + +* **Swagger UI**:服务于 `/docs`。 + * 可以使用参数 `docs_url` 设置它的 URL。 + * 可以通过设置 `docs_url=None` 禁用它。 +* ReDoc:服务于 `/redoc`。 + * 可以使用参数 `redoc_url` 设置它的 URL。 + * 可以通过设置 `redoc_url=None` 禁用它。 + +例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: + +```Python hl_lines="3" +{!../../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index c9a7e7725..7cc6cac42 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/docs/zh/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * 它可以对该**响应**做些什么或者执行任何需要的代码. * 然后它返回这个 **响应**. -!!! note "技术细节" - 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. +/// note | "技术细节" - 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. +如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. + +如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. + +/// ## 创建中间件 @@ -32,15 +35,21 @@ {!../../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - 请记住可以 用'X-' 前缀添加专有自定义请求头. +/// tip + +请记住可以 用'X-' 前缀添加专有自定义请求头. + +但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. + +/// + +/// note | "技术细节" - 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. +你也可以使用 `from starlette.requests import Request`. -!!! note "技术细节" - 你也可以使用 `from starlette.requests import Request`. +**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. - **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. +/// ### 在 `response` 的前和后 diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md index f79b0e692..ac0177128 100644 --- a/docs/zh/docs/tutorial/path-operation-configuration.md +++ b/docs/zh/docs/tutorial/path-operation-configuration.md @@ -2,9 +2,11 @@ *路径操作装饰器*支持多种配置参数。 -!!! warning "警告" +/// warning | "警告" - 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 +注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 + +/// ## `status_code` 状态码 @@ -20,11 +22,13 @@ 状态码在响应中使用,并会被添加到 OpenAPI 概图。 -!!! note "技术细节" +/// note | "技术细节" + +也可以使用 `from starlette import status` 导入状态码。 - 也可以使用 `from starlette import status` 导入状态码。 +**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 - **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 +/// ## `tags` 参数 @@ -68,15 +72,19 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: {!../../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "说明" +/// info | "说明" + +注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 + +/// - 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 +/// check | "检查" -!!! check "检查" +OpenAPI 规定每个*路径操作*都要有响应描述。 - OpenAPI 规定每个*路径操作*都要有响应描述。 +如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 - 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 +/// diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 9b41ad7cf..6310ad8d2 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -6,41 +6,57 @@ 首先,从 `fastapi` 导入 `Path`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="1 3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3-4" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// + +```Python hl_lines="3" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// ## 声明元数据 @@ -48,48 +64,67 @@ 例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// -!!! note - 路径参数总是必需的,因为它必须是路径的一部分。 +```Python hl_lines="8" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - 所以,你应该在声明时使用 `...` 将其标记为必需参数。 +//// - 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +路径参数总是必需的,因为它必须是路径的一部分。 + +所以,你应该在声明时使用 `...` 将其标记为必需参数。 + +然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 + +/// ## 按需对参数排序 @@ -107,14 +142,19 @@ 因此,你可以将函数声明为: -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// + +```Python hl_lines="7" +{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// ## 按需对参数排序的技巧 @@ -174,18 +214,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `lt`:小于(`l`ess `t`han) * `le`:小于等于(`l`ess than or `e`qual) -!!! info - `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 +/// info + +`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 + +而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 + +/// + +/// note | "技术细节" - 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 +当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 -!!! note "技术细节" - 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 +当被调用时,它们返回同名类的实例。 - 当被调用时,它们返回同名类的实例。 +如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 - 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 +因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 - 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 +这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 - 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 +/// diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 12a08b4a3..091dcbeb0 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -24,9 +24,11 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 本例把 `item_id` 的类型声明为 `int`。 -!!! check "检查" +/// check | "检查" - 类型声明将为函数提供错误检查、代码补全等编辑器支持。 +类型声明将为函数提供错误检查、代码补全等编辑器支持。 + +/// ## 数据转换 @@ -36,11 +38,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** {"item_id":3} ``` -!!! check "检查" +/// check | "检查" + +注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 - 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 +**FastAPI** 通过类型声明自动**解析**请求中的数据。 - **FastAPI** 通过类型声明自动**解析**请求中的数据。 +/// ## 数据校验 @@ -65,13 +69,15 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。 -!!! check "检查" +/// check | "检查" - **FastAPI** 使用 Python 类型声明实现了数据校验。 +**FastAPI** 使用 Python 类型声明实现了数据校验。 - 注意,上面的错误清晰地指出了未通过校验的具体原因。 +注意,上面的错误清晰地指出了未通过校验的具体原因。 - 这在开发调试与 API 交互的代码时非常有用。 +这在开发调试与 API 交互的代码时非常有用。 + +/// ## 查看文档 @@ -79,11 +85,13 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** -!!! check "检查" +/// check | "检查" + +还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 - 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 +注意,路径参数的类型是整数。 - 注意,路径参数的类型是整数。 +/// ## 基于标准的好处,备选文档 @@ -135,13 +143,17 @@ FastAPI 充分地利用了 枚举(即 enums)。 +Python 3.4 及之后版本支持枚举(即 enums)。 -!!! tip "提示" +/// - **AlexNet**、**ResNet**、**LeNet** 是机器学习模型。 +/// tip | "提示" + +**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。 + +/// ### 声明*路径参数* @@ -177,9 +189,11 @@ FastAPI 充分地利用了 ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// 查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。 @@ -98,8 +102,11 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - 具有默认值还会使该参数成为可选参数。 +/// note + +具有默认值还会使该参数成为可选参数。 + +/// ## 声明为必需参数 @@ -135,9 +142,12 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 - Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 +/// info + +如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 +Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 + +/// 这将使 **FastAPI** 知道此查询参数是必需的。 @@ -151,8 +161,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006c.py!} ``` -!!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 +/// tip + +Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 + +/// ### 使用Pydantic中的`Required`代替省略号(`...`) @@ -162,9 +175,11 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// tip + +请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// ## 查询参数列表 / 多个值 @@ -195,8 +210,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 +/// tip + +要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 + +/// 交互式 API 文档将会相应地进行更新,以允许使用多个值: @@ -235,10 +253,13 @@ http://localhost:8000/items/ {!../../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - 请记住,在这种情况下 FastAPI 将不会检查列表的内容。 +/// note - 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 +请记住,在这种情况下 FastAPI 将不会检查列表的内容。 + +例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 + +/// ## 声明更多元数据 @@ -246,10 +267,13 @@ http://localhost:8000/items/ 这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。 -!!! note - 请记住,不同的工具对 OpenAPI 的支持程度可能不同。 +/// note + +请记住,不同的工具对 OpenAPI 的支持程度可能不同。 + +其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 - 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 +/// 你可以添加 `title`: diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index 8b2528c9a..6853e3899 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -63,48 +63,58 @@ http://127.0.0.1:8000/items/?skip=20 同理,把默认值设为 `None` 即可声明**可选的**查询参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial002.py!} +``` + +//// 本例中,查询参数 `q` 是可选的,默认值为 `None`。 -!!! check "检查" +/// check | "检查" + +注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 - 注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 +/// -!!! note "笔记" +/// note | "笔记" - 因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 +因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 - FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 +FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 + +/// ## 查询参数类型转换 参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +```Python hl_lines="9" +{!> ../../../docs_src/query_params/tutorial003.py!} +``` +//// 本例中,访问: @@ -147,18 +157,21 @@ http://127.0.0.1:8000/items/foo?short=yes FastAPI 通过参数名进行检测: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +```Python hl_lines="6 8" +{!> ../../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +```Python hl_lines="8 10" +{!> ../../../docs_src/query_params/tutorial004.py!} +``` +//// ## 必选查询参数 @@ -214,17 +227,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_params/tutorial006.py!} +``` + +//// 本例中有 3 个查询参数: @@ -232,5 +249,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`,默认值为 `0` 的 `int` 类型参数 * `limit`,可选的 `int` 类型参数 -!!! tip "提示" - 还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 +/// tip | "提示" + +还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 + +/// diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 1cd3518cf..d5d0fb671 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -2,13 +2,15 @@ `File` 用于定义客户端的上传文件。 -!!! info "说明" +/// info | "说明" - 因为上传文件以「表单数据」形式发送。 +因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 `python-multipart`。 +所以接收上传文件,要预先安装 `python-multipart`。 - 例如: `pip install python-multipart`。 +例如: `pip install python-multipart`。 + +/// ## 导入 `File` @@ -26,15 +28,19 @@ {!../../../docs_src/request_files/tutorial001.py!} ``` -!!! info "说明" +/// info | "说明" + +`File` 是直接继承自 `Form` 的类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 - `File` 是直接继承自 `Form` 的类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 +/// tip | "提示" -!!! tip "提示" +声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// 文件作为「表单数据」上传。 @@ -92,13 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 技术细节" +/// note | "`async` 技术细节" + +使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 + +/// - 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 +/// note | "Starlette 技术细节" -!!! note "Starlette 技术细节" +**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 - **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 +/// ## 什么是 「表单数据」 @@ -106,35 +116,43 @@ contents = myfile.file.read() **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | "技术细节" - 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 +不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 - 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 +但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 - 编码和表单字段详见 MDN Web 文档的 POST 小节。 +编码和表单字段详见 MDN Web 文档的 POST 小节。 -!!! warning "警告" +/// - 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 +/// warning | "警告" - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 + +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 + +/// ## 可选文件上传 您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7 14" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +//// ## 带有额外元数据的 `UploadFile` @@ -152,42 +170,52 @@ FastAPI 支持同时上传多个文件。 上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// 接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 -!!! note "技术细节" +/// note | "技术细节" - 也可以使用 `from starlette.responses import HTMLResponse`。 +也可以使用 `from starlette.responses import HTMLResponse`。 - `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 +`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 + +/// ### 带有额外元数据的多文件上传 和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index f58593669..723cf5b18 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -2,11 +2,13 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 -!!! info "说明" +/// info | "说明" - 接收上传文件或表单数据,要预先安装 `python-multipart`。 +接收上传文件或表单数据,要预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `File` 与 `Form` @@ -26,11 +28,13 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 声明文件可以使用 `bytes` 或 `UploadFile` 。 -!!! warning "警告" +/// warning | "警告" + +可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index e4fcd88ff..6cc472ac1 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -2,11 +2,13 @@ 接收的不是 JSON,而是表单字段时,要使用 `Form`。 -!!! info "说明" +/// info | "说明" - 要使用表单,需预先安装 `python-multipart`。 +要使用表单,需预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `Form` @@ -30,13 +32,17 @@ 使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。 -!!! info "说明" +/// info | "说明" + +`Form` 是直接继承自 `Body` 的类。 + +/// - `Form` 是直接继承自 `Body` 的类。 +/// tip | "提示" -!!! tip "提示" +声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// ## 关于 "表单字段" @@ -44,19 +50,23 @@ **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | "技术细节" + +表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 + +但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 - 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 +编码和表单字段详见 MDN Web 文档的 POST小节。 - 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 +/// - 编码和表单字段详见 MDN Web 文档的 POST小节。 +/// warning | "警告" -!!! warning "警告" +可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index 0f1b3b4b9..3c196c964 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -8,26 +8,35 @@ * `@app.delete()` * 等等。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../../docs_src/response_model/tutorial001.py!} +``` -!!! note - 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +//// + +/// note + +注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 + +/// 它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。 @@ -42,8 +51,11 @@ FastAPI 将使用此 `response_model` 来: * 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。 -!!! note "技术细节" - 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 +/// note | "技术细节" + +响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 + +/// ## 返回与输入相同的数据 @@ -65,52 +77,67 @@ FastAPI 将使用此 `response_model` 来: 但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。 -!!! danger - 永远不要存储用户的明文密码,也不要在响应中发送密码。 +/// danger + +永远不要存储用户的明文密码,也不要在响应中发送密码。 + +/// ## 添加输出模型 相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// 这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../../docs_src/response_model/tutorial003.py!} +``` + +//// 因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。 @@ -159,16 +186,22 @@ FastAPI 将使用此 `response_model` 来: } ``` -!!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 +/// info + +FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 -!!! info - 你还可以使用: +/// - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +/// info - 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 +你还可以使用: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 + +/// #### 默认值字段有实际值的数据 @@ -203,10 +236,13 @@ FastAPI 将使用此 `response_model` 来: 因此,它们将包含在 JSON 响应中。 -!!! tip - 请注意默认值可以是任何值,而不仅是`None`。 +/// tip + +请注意默认值可以是任何值,而不仅是`None`。 + +它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 - 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 +/// ### `response_model_include` 和 `response_model_exclude` @@ -216,21 +252,27 @@ FastAPI 将使用此 `response_model` 来: 如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。 -!!! tip - 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 +/// tip - 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 +但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 - 这也适用于作用类似的 `response_model_by_alias`。 +这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 + +这也适用于作用类似的 `response_model_by_alias`。 + +/// ```Python hl_lines="31 37" {!../../../docs_src/response_model/tutorial005.py!} ``` -!!! tip - `{"name", "description"}` 语法创建一个具有这两个值的 `set`。 +/// tip + +`{"name", "description"}` 语法创建一个具有这两个值的 `set`。 + +等同于 `set(["name", "description"])`。 - 等同于 `set(["name", "description"])`。 +/// #### 使用 `list` 而不是 `set` diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index cc23231b4..506cd4a43 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -12,15 +12,19 @@ {!../../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "笔记" +/// note | "笔记" - 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 +注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 + +/// `status_code` 参数接收表示 HTTP 状态码的数字。 -!!! info "说明" +/// info | "说明" + +`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 - `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 +/// 它可以: @@ -29,17 +33,21 @@ -!!! note "笔记" +/// note | "笔记" + +某些响应状态码表示响应没有响应体(参阅下一章)。 - 某些响应状态码表示响应没有响应体(参阅下一章)。 +FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 - FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 +/// ## 关于 HTTP 状态码 -!!! note "笔记" +/// note | "笔记" - 如果已经了解 HTTP 状态码,请跳到下一章。 +如果已经了解 HTTP 状态码,请跳到下一章。 + +/// 在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 @@ -58,9 +66,11 @@ * 对于来自客户端的一般错误,可以只使用 `400` * `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -!!! tip "提示" +/// tip | "提示" + +状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 - 状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 +/// ## 状态码名称快捷方式 @@ -84,11 +94,13 @@ -!!! note "技术细节" +/// note | "技术细节" + +也可以使用 `from starlette import status`。 - 也可以使用 `from starlette import status`。 +为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 - 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 +/// ## 更改默认状态码 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index ae204dc61..6063bd731 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -10,17 +10,21 @@ 您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// 这些额外的信息将按原样添加到输出的JSON模式中。 @@ -28,20 +32,27 @@ 在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// -!!! warning - 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 +/// warning + +请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 + +/// ## `Body` 额外参数 @@ -49,41 +60,57 @@ 比如,你可以将请求体的一个 `example` 传递给 `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="23-28" +{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="18-23" +{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="20-25" +{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// ## 文档 UI 中的例子 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index f28cc24f8..266a5fcdf 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ 把下面的示例代码复制到 `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/security/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python +{!> ../../../docs_src/security/tutorial001.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// ## 运行 -!!! info "说明" +/// info | "说明" + +先安装 `python-multipart`。 - 先安装 `python-multipart`。 +安装命令: `pip install python-multipart`。 - 安装命令: `pip install python-multipart`。 +这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 - 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 +/// 用下面的命令运行该示例: @@ -71,19 +82,23 @@ $ uvicorn main:app --reload -!!! check "Authorize 按钮!" +/// check | "Authorize 按钮!" - 页面右上角出现了一个「**Authorize**」按钮。 +页面右上角出现了一个「**Authorize**」按钮。 - *路径操作*的右上角也出现了一个可以点击的小锁图标。 +*路径操作*的右上角也出现了一个可以点击的小锁图标。 + +/// 点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段: -!!! note "笔记" +/// note | "笔记" + +目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 - 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 +/// 虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。 @@ -125,15 +140,17 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 -!!! info "说明" +/// info | "说明" - `Bearer` 令牌不是唯一的选择。 +`Bearer` 令牌不是唯一的选择。 - 但它是最适合这个用例的方案。 +但它是最适合这个用例的方案。 - 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 +甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 - 本例中,**FastAPI** 还提供了构建工具。 +本例中,**FastAPI** 还提供了构建工具。 + +/// 创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。 @@ -141,23 +158,27 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 {!../../../docs_src/security/tutorial001.py!} ``` -!!! tip "提示" +/// tip | "提示" + +在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 - 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 +因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 - 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 +使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 - 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 +/// 该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。 接下来,学习如何创建实际的路径操作。 -!!! info "说明" +/// info | "说明" - 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 +严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 - 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 +这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 + +/// `oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。 @@ -181,11 +202,13 @@ oauth2_scheme(some, parameters) **FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 -!!! info "技术细节" +/// info | "技术细节" + +**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 - **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 +所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 - 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 +/// ## 实现的操作 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 1f17f5bd9..f8094e86a 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -55,18 +55,21 @@ 这有助于在函数内部使用代码补全和类型检查。 -!!! tip "提示" +/// tip | "提示" - 还记得请求体也是使用 Pydantic 模型声明的吧。 +还记得请求体也是使用 Pydantic 模型声明的吧。 - 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 +放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 -!!! check "检查" +/// - 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +/// check | "检查" - 而不是局限于只能有一个返回该类型数据的依赖项。 +依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +而不是局限于只能有一个返回该类型数据的依赖项。 + +/// ## 其它模型 diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md index 0595f5f63..e888a4fe9 100644 --- a/docs/zh/docs/tutorial/security/index.md +++ b/docs/zh/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法 OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。 -!!! tip - 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 +/// tip +在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI 定义了以下安全方案: * 此自动发现机制是 OpenID Connect 规范中定义的内容。 -!!! tip - 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 +/// tip + +集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 + +最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 - 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 +/// ## **FastAPI** 实用工具 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 117f74d3e..690bd1789 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -40,11 +40,13 @@ $ pip install pyjwt -!!! info "说明" +/// info | "说明" - 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 +如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 - 您可以在 PyJWT Installation docs 获得更多信息。 +您可以在 PyJWT Installation docs 获得更多信息。 + +/// ## 密码哈希 @@ -80,13 +82,15 @@ $ pip install passlib[bcrypt] -!!! tip "提示" +/// tip | "提示" + +`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 - `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 +例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 - 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 +并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 - 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 +/// ## 密码哈希与校验 @@ -94,13 +98,15 @@ $ pip install passlib[bcrypt] 创建用于密码哈希和身份校验的 PassLib **上下文**。 -!!! tip "提示" +/// tip | "提示" + +PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 - PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 +例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 - 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 +同时,这些功能都是兼容的。 - 同时,这些功能都是兼容的。 +/// 接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。 @@ -108,45 +114,63 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 50 57-58 61-62 71-77" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="8 50 57-58 61-62 71-77" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../../docs_src/security/tutorial004.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="8 49 56-57 60-61 70-76" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +/// note | "笔记" -!!! note "笔记" +查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 - 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 +/// ## 处理 JWT 令牌 @@ -188,41 +212,57 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 7 14-16 30-32 80-88" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="3 6 12-14 28-30 78-86" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="4 7 14-16 30-32 80-88" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="3 6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="4 7 13-15 29-31 79-87" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ## 更新 `/token` *路径操作* @@ -230,41 +270,57 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py310.py!} - ``` +```Python hl_lines="118-133" +{!> ../../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="119-134" +{!> ../../../docs_src/security/tutorial004_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="118-133" - {!> ../../../docs_src/security/tutorial004_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="119-134" - {!> ../../../docs_src/security/tutorial004_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="115-130" +{!> ../../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="116-131" +{!> ../../../docs_src/security/tutorial004.py!} +``` - ```Python hl_lines="116-131" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// ### JWT `sub` 的技术细节 @@ -302,9 +358,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 用户名: `johndoe` 密码: `secret` -!!! check "检查" +/// check | "检查" + +注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 - 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 +/// @@ -325,9 +383,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 -!!! note "笔记" +/// note | "笔记" + +注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 - 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 +/// ## `scopes` 高级用法 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index 751767ea2..261421dad 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -32,15 +32,17 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | "说明" - OAuth2 中,**作用域**只是声明指定权限的字符串。 +OAuth2 中,**作用域**只是声明指定权限的字符串。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 这些细节只是特定的实现方式。 +这些细节只是特定的实现方式。 - 对 OAuth2 来说,都只是字符串而已。 +对 OAuth2 来说,都只是字符串而已。 + +/// ## 获取 `username` 和 `password` 的代码 @@ -61,32 +63,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 * 可选的 `grant_type` -!!! tip "提示" +/// tip | "提示" + +实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 +如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 - 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 +/// * 可选的 `client_id`(本例未使用) * 可选的 `client_secret`(本例未使用) -!!! info "说明" +/// info | "说明" - `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 +`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 +**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 +但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 - 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 +但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 + +/// ### 使用表单数据 -!!! tip "提示" +/// tip | "提示" + +`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 +本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 - 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 +/// 现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 @@ -142,9 +150,11 @@ UserInDB( ) ``` -!!! info "说明" +/// info | "说明" - `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 +`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 + +/// ## 返回 Token @@ -156,25 +166,29 @@ UserInDB( 本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 -!!! tip "提示" +/// tip | "提示" + +下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 - 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 +但现在,仅关注所需的特定细节。 - 但现在,仅关注所需的特定细节。 +/// ```Python hl_lines="85" {!../../../docs_src/security/tutorial003.py!} ``` -!!! tip "提示" +/// tip | "提示" - 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 +按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 +这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 +这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 - **FastAPI** 则负责处理其它的工作。 +**FastAPI** 则负责处理其它的工作。 + +/// ## 更新依赖项 @@ -192,21 +206,23 @@ UserInDB( {!../../../docs_src/security/tutorial003.py!} ``` -!!! info "说明" +/// info | "说明" + +此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 +任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 +本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 +实际上,忽略这个附加响应头,也不会有什么问题。 - 实际上,忽略这个附加响应头,也不会有什么问题。 +之所以在此提供这个附加响应头,是为了符合规范的要求。 - 之所以在此提供这个附加响应头,是为了符合规范的要求。 +说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 +这就是遵循标准的好处…… - 这就是遵循标准的好处…… +/// ## 实际效果 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 8629b23fa..45ec71f7c 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,11 +1,14 @@ # SQL (关系型) 数据库 -!!! info - 这些文档即将被更新。🎉 +/// info - 当前版本假设Pydantic v1和SQLAlchemy版本小于2。 +这些文档即将被更新。🎉 - 新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 +当前版本假设Pydantic v1和SQLAlchemy版本小于2。 + +新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 + +/// **FastAPI**不需要你使用SQL(关系型)数据库。 @@ -25,11 +28,17 @@ 稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 -!!! tip - 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql +/// tip + +这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql + +/// -!!! note - 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 +/// note + +请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 + +/// ## ORMs(对象关系映射) @@ -63,8 +72,11 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 以类似的方式,您也可以使用任何其他 ORM。 -!!! tip - 在文档中也有一篇使用 Peewee 的等效的文章。 +/// tip + +在文档中也有一篇使用 Peewee 的等效的文章。 + +/// ## 文件结构 @@ -129,9 +141,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 -!!! tip +/// tip + +如果您想使用不同的数据库,这是就是您必须修改的地方。 - 如果您想使用不同的数据库,这是就是您必须修改的地方。 +/// ### 创建 SQLAlchemy 引擎 @@ -153,15 +167,17 @@ connect_args={"check_same_thread": False} ...仅用于`SQLite`,在其他数据库不需要它。 -!!! info "技术细节" +/// info | "技术细节" + +默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 +这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 +但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 +此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 +/// ### 创建一个`SessionLocal`类 @@ -197,10 +213,13 @@ connect_args={"check_same_thread": False} 我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 -!!! tip - SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 +/// tip - 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 +SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 + +而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 + +/// 从`database`(来自上面的`database.py`文件)导入`Base`。 @@ -250,12 +269,15 @@ connect_args={"check_same_thread": False} 现在让我们查看一下文件`sql_app/schemas.py`。 -!!! tip - 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 +/// tip + +为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 - 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 +这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 - 因此,这将帮助我们在使用两者时避免混淆。 +因此,这将帮助我们在使用两者时避免混淆。 + +/// ### 创建初始 Pydantic*模型*/模式 @@ -267,23 +289,29 @@ connect_args={"check_same_thread": False} 但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// #### SQLAlchemy 风格和 Pydantic 风格 @@ -311,26 +339,35 @@ name: str 不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13-15 29-32" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="15-17 31-34" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` -!!! tip - 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 +//// + +/// tip + +请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 + +/// ### 使用 Pydantic 的`orm_mode` @@ -340,32 +377,41 @@ name: str 在`Config`类中,设置属性`orm_mode = True`。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 17-18 29 34-35" +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python hl_lines="15 19-20 31 36-37" +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +请注意,它使用`=`分配一个值,例如: -!!! tip - 请注意,它使用`=`分配一个值,例如: +`orm_mode = True` - `orm_mode = True` +它不使用之前的`:`来类型声明。 - 它不使用之前的`:`来类型声明。 +这是设置配置值,而不是声明类型。 - 这是设置配置值,而不是声明类型。 +/// Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 @@ -431,8 +477,11 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 +/// tip + +通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 + +/// ### 创建数据 @@ -449,34 +498,43 @@ current_user.items {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 +/// tip + +SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 + +但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 + +然后将hashed_password参数与要保存的值一起传递。 + +/// + +/// warning - 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 +此示例不安全,密码未经过哈希处理。 - 然后将hashed_password参数与要保存的值一起传递。 +在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 -!!! warning - 此示例不安全,密码未经过哈希处理。 +有关更多详细信息,请返回教程中的安全部分。 - 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 +在这里,我们只关注数据库的工具和机制。 - 有关更多详细信息,请返回教程中的安全部分。 +/// - 在这里,我们只关注数据库的工具和机制。 +/// tip -!!! tip - 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: +这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - `item.dict()` +`item.dict()` - 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: +然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - `Item(**item.dict())` +`Item(**item.dict())` - 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: +然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: - `Item(**item.dict(), owner_id=user_id)` +`Item(**item.dict(), owner_id=user_id)` + +/// ## 主**FastAPI**应用程序 @@ -486,17 +544,21 @@ current_user.items 以非常简单的方式创建数据库表: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// #### Alembic 注意 @@ -520,63 +582,81 @@ current_user.items 我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13-18" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-20" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +/// info -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - 然后我们在finally块中关闭它。 +然后我们在finally块中关闭它。 - 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 +通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 - 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) +但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) + +/// *然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 *这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="22 30 36 45 51" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ -!!! info "技术细节" - 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 +```Python hl_lines="24 32 38 47 53" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 +//// + +/// info | "技术细节" + +参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 + +但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 + +/// ### 创建您的**FastAPI** *路径操作* 现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// 我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 @@ -584,15 +664,21 @@ current_user.items 这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 -!!! tip - 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 +/// tip + +请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 + +但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 + +/// + +/// tip - 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 +另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. -!!! tip - 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. +但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 - 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 +/// ### 关于 `def` 对比 `async def` @@ -621,11 +707,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) +/// info -!!! note "Very Technical Details" - 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 +如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) + +/// + +/// note | "Very Technical Details" + +如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 + +/// ## 迁移 @@ -659,23 +751,29 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/schemas.py`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python +{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// * `sql_app/crud.py`: @@ -685,25 +783,31 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// ## 执行项目 您可以复制这些代码并按原样使用它。 -!!! info +/// info + +事实上,这里的代码只是大多数测试代码的一部分。 - 事实上,这里的代码只是大多数测试代码的一部分。 +/// 你可以用 Uvicorn 运行它: @@ -744,24 +848,31 @@ $ uvicorn sql_app.main:app --reload 我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="12-20" +{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +```Python hl_lines="14-22" +{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +然后我们在finally块中关闭它。 - 然后我们在finally块中关闭它。 +通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 +/// ### 关于`request.state` @@ -782,10 +893,16 @@ $ uvicorn sql_app.main:app --reload * 将为每个请求创建一个连接。 * 即使处理该请求的*路径操作*不需要数据库。 -!!! tip - 最好使用带有yield的依赖项,如果这足够满足用例需求 +/// tip + +最好使用带有yield的依赖项,如果这足够满足用例需求 + +/// + +/// info + +带有`yield`的依赖项是最近刚加入**FastAPI**中的。 -!!! info - 带有`yield`的依赖项是最近刚加入**FastAPI**中的。 +所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 - 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 +/// diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md index e7c5c3f0a..3d14f34d8 100644 --- a/docs/zh/docs/tutorial/static-files.md +++ b/docs/zh/docs/tutorial/static-files.md @@ -11,10 +11,13 @@ {!../../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以用 `from starlette.staticfiles import StaticFiles`。 +/// note | "技术细节" - **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 +你也可以用 `from starlette.staticfiles import StaticFiles`。 + +**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 + +/// ### 什么是"挂载"(Mounting) diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 69841978c..18c35e8c6 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## 使用 `TestClient` -!!! info "信息" - 要使用 `TestClient`,先要安装 `httpx`. +/// info | "信息" - 例:`pip install httpx`. +要使用 `TestClient`,先要安装 `httpx`. + +例:`pip install httpx`. + +/// 导入 `TestClient`. @@ -27,20 +30,29 @@ {!../../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "提示" - 注意测试函数是普通的 `def`,不是 `async def`。 +/// tip | "提示" + +注意测试函数是普通的 `def`,不是 `async def`。 + +还有client的调用也是普通的调用,不是用 `await`。 + +这让你可以直接使用 `pytest` 而不会遇到麻烦。 + +/// + +/// note | "技术细节" + +你也可以用 `from starlette.testclient import TestClient`。 - 还有client的调用也是普通的调用,不是用 `await`。 +**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 - 这让你可以直接使用 `pytest` 而不会遇到麻烦。 +/// -!!! note "技术细节" - 你也可以用 `from starlette.testclient import TestClient`。 +/// tip | "提示" - **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 +除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 -!!! tip "提示" - 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 +/// ## 分离测试 @@ -110,41 +122,57 @@ 所有*路径操作* 都需要一个`X-Token` 头。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "提示" - Prefer to use the `Annotated` version if possible. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | "提示" - !!! tip "提示" - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "提示" + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 扩展后的测试文件 @@ -168,10 +196,13 @@ 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档. -!!! info "信息" - 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 +/// info | "信息" + +注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 + +如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 - 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 +/// ## 运行起来 diff --git a/requirements-docs-insiders.txt b/requirements-docs-insiders.txt new file mode 100644 index 000000000..d8d3c37a9 --- /dev/null +++ b/requirements-docs-insiders.txt @@ -0,0 +1,3 @@ +git+https://${TOKEN}@github.com/squidfunk/mkdocs-material-insiders.git@9.5.30-insiders-4.53.11 +git+https://${TOKEN}@github.com/pawamoy-insiders/griffe-typing-deprecated.git +git+https://${TOKEN}@github.com/pawamoy-insiders/mkdocstrings-python.git diff --git a/requirements-docs.txt b/requirements-docs.txt index c672f0ef7..a7ef7ef2e 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -3,16 +3,16 @@ mkdocs-material==9.5.18 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer >=0.12.0 +typer == 0.12.3 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs pillow==10.3.0 # For image processing by Material for MkDocs -cairosvg==2.7.0 -mkdocstrings[python]==0.24.3 -griffe-typingdoc==0.2.2 +cairosvg==2.7.1 +mkdocstrings[python]==0.25.1 +griffe-typingdoc==0.2.5 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 diff --git a/scripts/docs.py b/scripts/docs.py index 59578a820..fd2dd78f1 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -11,9 +11,6 @@ from multiprocessing import Pool from pathlib import Path from typing import Any, Dict, List, Optional, Union -import mkdocs.commands.build -import mkdocs.commands.serve -import mkdocs.config import mkdocs.utils import typer import yaml @@ -165,6 +162,13 @@ def generate_readme_content() -> str: pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content + # Remove content between and + new_content = re.sub( + r".*?", + "", + new_content, + flags=re.DOTALL, + ) return new_content @@ -258,12 +262,15 @@ def live( en. """ # Enable line numbers during local development to make it easier to highlight - os.environ["LINENUMS"] = "true" if lang is None: lang = "en" lang_path: Path = docs_path / lang - os.chdir(lang_path) - mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") + subprocess.run( + ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008", "--dirty"], + env={**os.environ, "LINENUMS": "true"}, + cwd=lang_path, + check=True, + ) def get_updated_config_content() -> Dict[str, Any]: From df419b739cf66108adac63d7ab81d62bced1f5a7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 6 Aug 2024 04:48:52 +0000 Subject: [PATCH 010/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 78e27ba7e..1fa24af65 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). ## 0.112.0 From 7ff5da8bf2b8bfe895e4621f630e9fc3f2c434f4 Mon Sep 17 00:00:00 2001 From: Dom Date: Tue, 6 Aug 2024 14:46:39 +0100 Subject: [PATCH 011/356] edit middleware docs code sample to use perf_counter as a timer --- docs_src/middleware/tutorial001.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py index 6bab3410a..e65a7dade 100644 --- a/docs_src/middleware/tutorial001.py +++ b/docs_src/middleware/tutorial001.py @@ -7,8 +7,8 @@ app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): - start_time = time.time() + start_time = time.perf_counter() response = await call_next(request) - process_time = time.time() - start_time + process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response From f0a146e4f8405aba8708e93cf163da70ee922dfe Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Wed, 7 Aug 2024 15:58:00 -0300 Subject: [PATCH 012/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/using-request-directly.md?= =?UTF-8?q?`=20(#11956)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/using-request-directly.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/pt/docs/advanced/using-request-directly.md diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..3dd0a8aef --- /dev/null +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -0,0 +1,58 @@ +# Utilizando o Request diretamente + +Até agora você declarou as partes da requisição que você precisa utilizando os seus tipos. + +Obtendo dados de: + +* Os parâmetros das rotas. +* Cabeçalhos (*Headers*). +* Cookies. +* etc. + +E ao fazer isso, o **FastAPI** está validando as informações, convertendo-as e gerando documentação para a sua API automaticamente. + +Porém há situações em que você possa precisar acessar o objeto `Request` diretamente. + +## Detalhes sobre o objeto `Request` + +Como o **FastAPI** é na verdade o **Starlette** por baixo, com camadas de diversas funcionalidades por cima, você pode utilizar o objeto `Request` do Starlette diretamente quando precisar. + +Isso significaria também que se você obtiver informações do objeto `Request` diretamente (ler o corpo da requisição por exemplo), as informações não serão validadas, convertidas ou documentadas (com o OpenAPI, para a interface de usuário automática da API) pelo FastAPI. + +Embora qualquer outro parâmetro declarado normalmente (o corpo da requisição com um modelo Pydantic, por exemplo) ainda seria validado, convertido, anotado, etc. + +Mas há situações específicas onde é útil utilizar o objeto `Request`. + +## Utilize o objeto `Request` diretamente + +Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro da sua *função de operação de rota*. + +Para isso você precisa acessar a requisição diretamente. + +```Python hl_lines="1 7-8" +{!../../../docs_src/using_request_directly/tutorial001.py!} +``` + +Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. + +/// tip | "Dica" + +Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. + +Assim, o parâmetro da rota será extraído, validado, convertido para o tipo especificado e anotado com OpenAPI. + +Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e além disso, obter o `Request` também. + +/// + +## Documentação do `Request` + +Você pode ler mais sobre os detalhes do objeto `Request` no site da documentação oficial do Starlette.. + +/// note | "Detalhes Técnicos" + +Você também pode utilizar `from starlette.requests import Request`. + +O **FastAPI** fornece isso diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// From a031d80e5c8a5fd80b8b63337759788976ff1e97 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 7 Aug 2024 18:58:22 +0000 Subject: [PATCH 013/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1fa24af65..abf41b858 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). * 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony). From f118154576d5c4d8a2f8a7e88d1f92a6a9d07d7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 7 Aug 2024 14:15:24 -0500 Subject: [PATCH 014/356] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Add=20deploy?= =?UTF-8?q?=20docs=20status=20and=20preview=20links=20to=20PRs=20(#11961)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 34 +++++---- scripts/comment_docs_deploy_url_in_pr.py | 31 -------- scripts/deploy_docs_status.py | 97 ++++++++++++++++++++++++ 3 files changed, 118 insertions(+), 44 deletions(-) delete mode 100644 scripts/comment_docs_deploy_url_in_pr.py create mode 100644 scripts/deploy_docs_status.py diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 7d8846bb3..85c0cebec 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -20,6 +20,25 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - uses: actions/cache@v4 + id: cache + with: + path: ${{ env.pythonLocation }} + key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 + - name: Install GitHub Actions dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: pip install -r requirements-github-actions.txt + - name: Deploy Docs Status Pending + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} + - name: Clean site run: | rm -rf ./site @@ -43,22 +62,11 @@ jobs: directory: './site' gitHubToken: ${{ secrets.GITHUB_TOKEN }} branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - - name: Set up Python - uses: actions/setup-python@v5 - with: - python-version: "3.11" - - uses: actions/cache@v4 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 - - name: Install GitHub Actions dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-github-actions.txt - name: Comment Deploy if: steps.deploy.outputs.url != '' - run: python ./scripts/comment_docs_deploy_url_in_pr.py + run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DEPLOY_URL: ${{ steps.deploy.outputs.url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} diff --git a/scripts/comment_docs_deploy_url_in_pr.py b/scripts/comment_docs_deploy_url_in_pr.py deleted file mode 100644 index 3148a3bb4..000000000 --- a/scripts/comment_docs_deploy_url_in_pr.py +++ /dev/null @@ -1,31 +0,0 @@ -import logging -import sys - -from github import Github -from pydantic import SecretStr -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - github_repository: str - github_token: SecretStr - deploy_url: str - commit_sha: str - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.model_dump_json()}") - g = Github(settings.github_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - use_pr = next( - (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None - ) - if not use_pr: - logging.error(f"No PR found for hash: {settings.commit_sha}") - sys.exit(0) - use_pr.as_issue().create_comment( - f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" - ) - logging.info("Finished") diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py new file mode 100644 index 000000000..b19989235 --- /dev/null +++ b/scripts/deploy_docs_status.py @@ -0,0 +1,97 @@ +import logging +import re + +from github import Github +from pydantic import SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + deploy_url: str | None = None + commit_sha: str + run_id: int + + +def main(): + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + use_pr = next( + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None + ) + if not use_pr: + logging.error(f"No PR found for hash: {settings.commit_sha}") + return + commits = list(use_pr.get_commits()) + current_commit = [c for c in commits if c.sha == settings.commit_sha][0] + run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if not settings.deploy_url: + current_commit.create_status( + state="pending", + description="Deploy Docs", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No deploy URL available yet") + return + current_commit.create_status( + state="success", + description="Deploy Docs", + context="deploy-docs", + target_url=run_url, + ) + + files = list(use_pr.get_files()) + docs_files = [f for f in files if f.filename.startswith("docs/")] + + lang_links: dict[str, list[str]] = {} + for f in docs_files: + match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) + assert match + lang = match.group(1) + path = match.group(2) + if path.endswith("index.md"): + path = path.replace("index.md", "") + else: + path = path.replace(".md", "/") + if lang == "en": + link = f"{settings.deploy_url}{path}" + else: + link = f"{settings.deploy_url}{lang}/{path}" + lang_links.setdefault(lang, []).append(link) + + links: list[str] = [] + en_links = lang_links.get("en", []) + en_links.sort() + links.extend(en_links) + + langs = list(lang_links.keys()) + langs.sort() + for lang in langs: + if lang == "en": + continue + current_lang_links = lang_links[lang] + current_lang_links.sort() + links.extend(current_lang_links) + + message = ( + f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" + ) + + if links: + message += "\n\n### Modified Pages\n\n" + message += "\n".join([f"* {link}" for link in links]) + + print(message) + use_pr.as_issue().create_comment(message) + + logging.info("Finished") + + +if __name__ == "__main__": + main() From 9e84537685348368b45d42e85c8306d6df07185d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 7 Aug 2024 19:15:50 +0000 Subject: [PATCH 015/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index abf41b858..62421ce72 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). From 13b56ab499fc0fda121787491fa25e3083f8272b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 7 Aug 2024 15:56:47 -0500 Subject: [PATCH 016/356] =?UTF-8?q?=F0=9F=94=92=EF=B8=8F=20Update=20permis?= =?UTF-8?q?sions=20for=20deploy-docs=20action=20(#11964)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 85c0cebec..f28262b2a 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -10,6 +10,7 @@ permissions: deployments: write issues: write pull-requests: write + statuses: write jobs: deploy-docs: From 0eddc02aca24698fc61915107eb5c14f574e1d9d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 7 Aug 2024 20:57:09 +0000 Subject: [PATCH 017/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 62421ce72..2ecd5e9a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). * 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo). From 58279670b6757dccb510721ec3461aac87c51c2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 7 Aug 2024 16:17:14 -0500 Subject: [PATCH 018/356] =?UTF-8?q?=F0=9F=94=A8=20Refactor=20script=20`dep?= =?UTF-8?q?loy=5Fdocs=5Fstatus.py`=20to=20account=20for=20deploy=20URLs=20?= =?UTF-8?q?with=20or=20without=20trailing=20slash=20(#11965)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/deploy_docs_status.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index b19989235..e00fa2be0 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -49,6 +49,7 @@ def main(): files = list(use_pr.get_files()) docs_files = [f for f in files if f.filename.startswith("docs/")] + deploy_url = settings.deploy_url.rstrip("/") lang_links: dict[str, list[str]] = {} for f in docs_files: match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) @@ -60,9 +61,9 @@ def main(): else: path = path.replace(".md", "/") if lang == "en": - link = f"{settings.deploy_url}{path}" + link = f"{deploy_url}/{path}" else: - link = f"{settings.deploy_url}{lang}/{path}" + link = f"{deploy_url}/{lang}/{path}" lang_links.setdefault(lang, []).append(link) links: list[str] = [] @@ -79,9 +80,7 @@ def main(): current_lang_links.sort() links.extend(current_lang_links) - message = ( - f"📝 Docs preview for commit {settings.commit_sha} at: {settings.deploy_url}" - ) + message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" if links: message += "\n\n### Modified Pages\n\n" From b7f035512a06b736257150ca9d51bbc9810bb987 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 7 Aug 2024 21:17:38 +0000 Subject: [PATCH 019/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2ecd5e9a0..01c6f50e7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo). From 8377c5237cb718b4dd212103b8bb2cedfd4091e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 7 Aug 2024 22:51:13 -0500 Subject: [PATCH 020/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01c6f50e7..5776f4308 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -44,7 +44,7 @@ pip install "fastapi[standard]" * This adds support for calling the CLI as: ```bash -python -m python +python -m fastapi ``` * And it upgrades `fastapi-cli[standard] >=0.0.5`. From 233bab7f419c5bf2f9167a850f83c06a7d2c2af0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 8 Aug 2024 18:28:14 -0500 Subject: [PATCH 021/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20docs-previews?= =?UTF-8?q?=20to=20handle=20no=20docs=20changes=20(#11975)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 2 +- scripts/deploy_docs_status.py | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index f28262b2a..d2953f284 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,10 +64,10 @@ jobs: gitHubToken: ${{ secrets.GITHUB_TOKEN }} branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - name: Comment Deploy - if: steps.deploy.outputs.url != '' run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DEPLOY_URL: ${{ steps.deploy.outputs.url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.run_id }} + IS_DONE: "true" diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index e00fa2be0..ef33fe43d 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -12,6 +12,7 @@ class Settings(BaseSettings): deploy_url: str | None = None commit_sha: str run_id: int + is_done: bool = False def main(): @@ -30,10 +31,19 @@ def main(): commits = list(use_pr.get_commits()) current_commit = [c for c in commits if c.sha == settings.commit_sha][0] run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if settings.is_done and not settings.deploy_url: + current_commit.create_status( + state="success", + description="No Docs Changes", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No docs changes found") + return if not settings.deploy_url: current_commit.create_status( state="pending", - description="Deploy Docs", + description="Deploying Docs", context="deploy-docs", target_url=run_url, ) @@ -41,7 +51,7 @@ def main(): return current_commit.create_status( state="success", - description="Deploy Docs", + description="Docs Deployed", context="deploy-docs", target_url=run_url, ) From fda1813e1345c69ac93b53966889207b2bf340d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 8 Aug 2024 23:28:35 +0000 Subject: [PATCH 022/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5776f4308..e0bdb46ed 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo). From 51563564c6cbe50472d07b324f8304dcd59ad67c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 8 Aug 2024 18:34:25 -0500 Subject: [PATCH 023/356] =?UTF-8?q?=F0=9F=91=B7=20Add=20alls-green=20for?= =?UTF-8?q?=20test-redistribute=20(#11974)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test-redistribute.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index 0cc5f866e..693f0c603 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -55,3 +55,15 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + + # https://github.com/marketplace/actions/alls-green#why + test-redistribute-alls-green: # This job does nothing and is only used for the branch protection + if: always() + needs: + - test-redistribute + runs-on: ubuntu-latest + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} From 4b5342b568494597d58cd824a6f9fbe00da76046 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 8 Aug 2024 23:34:46 +0000 Subject: [PATCH 024/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0bdb46ed..8a467a1f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). * 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo). From 4f9ca032d6bbc6061a703780b5d74ac3264cdeb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 8 Aug 2024 20:42:26 -0500 Subject: [PATCH 025/356] =?UTF-8?q?=F0=9F=92=A1=20Add=20comment=20about=20?= =?UTF-8?q?custom=20Termynal=20line-height=20(#11976)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/css/termynal.css | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index af2fbe670..8534f9102 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,7 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + /* Custom line-height */ line-height: 1.2; } From 0b30cad9d218a4d267e399eb4796d91fcc97879d Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 9 Aug 2024 01:43:55 +0000 Subject: [PATCH 026/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8a467a1f6..a0176364c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). * 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo). From 8b6d9ba7898a130e7e3b2ce59d3a84c4476f7142 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 9 Aug 2024 10:52:41 -0500 Subject: [PATCH 027/356] =?UTF-8?q?=F0=9F=90=9B=20Fix=20deploy=20docs=20pr?= =?UTF-8?q?eviews=20script=20to=20handle=20mkdocs.yml=20files=20(#11984)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/deploy_docs_status.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index ef33fe43d..19dffbcb9 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -63,7 +63,8 @@ def main(): lang_links: dict[str, list[str]] = {} for f in docs_files: match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) - assert match + if not match: + continue lang = match.group(1) path = match.group(2) if path.endswith("index.md"): From 4cbb846d9eb5e2544ad93b3b0c0a7c415bc5c16e Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 9 Aug 2024 15:54:10 +0000 Subject: [PATCH 028/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a0176364c..c3b74ff73 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). * 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo). From e06e0b1c4a49bad052519afad67ef4dfe0bf33f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 9 Aug 2024 11:53:58 -0500 Subject: [PATCH 029/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20MkDocs=20instan?= =?UTF-8?q?t=20previews=20(#11982)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.insiders.yml | 2 +- docs/en/mkdocs.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index 18c6d3f53..4cec588fa 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -9,4 +9,4 @@ markdown_extensions: material.extensions.preview: targets: include: - - ./* + - "*" diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 782d4ef87..d37d7f42f 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -35,7 +35,7 @@ theme: - navigation.indexes - navigation.instant - navigation.instant.prefetch - - navigation.instant.preview + # - navigation.instant.preview - navigation.instant.progress - navigation.path - navigation.tabs From 6d9dc39fcb3eb3bcd9c2a693683d68311d1618e0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 9 Aug 2024 16:54:22 +0000 Subject: [PATCH 030/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3b74ff73..c978ad12c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Internal +* 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). * 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo). From 4ec134426d6c44a2f7d7c532933ae831e2c6be84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 9 Aug 2024 16:29:09 -0500 Subject: [PATCH 031/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20about=20?= =?UTF-8?q?discussions=20questions=20(#11985)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management-tasks.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 2c91cab72..815bad539 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -280,8 +280,4 @@ Dependabot will create PRs to update dependencies for several things, and those When a question in GitHub Discussions has been answered, mark the answer by clicking "Mark as answer". -Many of the current Discussion Questions were migrated from old issues. Many have the label `answered`, that means they were answered when they were issues, but now in GitHub Discussions, it's not known what is the actual response from the messages. - -You can filter discussions by [`Questions` that are `Unanswered` and have the label `answered`](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aopen+label%3Aanswered+is%3Aunanswered). - -All of those discussions already have an answer in the conversation, you can find it and mark it with the "Mark as answer" button. +You can filter discussions by `Questions` that are `Unanswered`. From 2b7fc3f340b7474a21e3e0e466eb4a64d90cf438 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 9 Aug 2024 21:29:31 +0000 Subject: [PATCH 032/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c978ad12c..ed66f7a21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). From 06fc1c2cc82bc585d0e695d57b1d7c7a0c2e0a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 9 Aug 2024 16:30:19 -0500 Subject: [PATCH 033/356] =?UTF-8?q?=F0=9F=94=A8=20Update=20docs.py=20scrip?= =?UTF-8?q?t=20to=20enable=20dirty=20reload=20conditionally=20(#11986)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/docs.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/docs.py b/scripts/docs.py index fd2dd78f1..5ef548889 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -251,6 +251,7 @@ def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ), + dirty: bool = False, ) -> None: """ Serve with livereload a docs site for a specific language. @@ -265,11 +266,12 @@ def live( if lang is None: lang = "en" lang_path: Path = docs_path / lang + # Enable line numbers during local development to make it easier to highlight + args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"] + if dirty: + args.append("--dirty") subprocess.run( - ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008", "--dirty"], - env={**os.environ, "LINENUMS": "true"}, - cwd=lang_path, - check=True, + args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True ) From 0e8b6d3bb8629168f2dcdc77dadc53b9a47ca84e Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 9 Aug 2024 21:32:11 +0000 Subject: [PATCH 034/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ed66f7a21..c861508b4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). * 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo). From b0a8e7356a3b2809045e68638cfcd2d6ff6de2e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 16:47:53 -0500 Subject: [PATCH 035/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20admonitions=20i?= =?UTF-8?q?n=20docs=20missing=20(#11998)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/deployment/docker.md | 7 +++++-- docs/em/docs/deployment/docker.md | 7 +++++-- docs/en/docs/contributing.md | 4 ++-- docs/en/docs/deployment/docker.md | 7 +++++-- docs/ja/docs/deployment/docker.md | 7 +++++-- docs/ko/docs/deployment/docker.md | 7 +++++-- docs/ko/docs/help-fastapi.md | 6 +++++- docs/pt/docs/deployment/docker.md | 7 +++++-- docs/ru/docs/deployment/docker.md | 7 +++++-- docs/zh/docs/deployment/docker.md | 7 +++++-- docs/zh/docs/deployment/https.md | 7 +++++-- 11 files changed, 52 insertions(+), 21 deletions(-) diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index 2186d16c5..c11dc4127 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. - !!! note "Hinweis" - Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + /// note | Hinweis + + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + /// Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index 6540761ac..2152f1a0e 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 🎛 💬 `pip` 🚫 🖊 ⏬ 📦 🌐, 👈 🕴 🚥 `pip` 🔜 🏃 🔄 ❎ 🎏 📦, ✋️ 👈 🚫 💼 🕐❔ 👷 ⏮️ 📦. - !!! note - `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + /// note + + `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + + /// `--upgrade` 🎛 💬 `pip` ♻ 📦 🚥 👫 ⏪ ❎. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index e86c34e48..9d6b773f7 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -458,9 +458,9 @@ Serving at: http://127.0.0.1:8008 * Do not change anything enclosed in "``" (inline code). -* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. +* In lines starting with `///` translate only the ` "... Text ..."` part. Leave the rest unchanged. -* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. +* You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box. * Do not change the paths in links to images, code files, Markdown documents. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 6140b1c42..253e25fe5 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -202,8 +202,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers. - !!! note - The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + /// note + + The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + + /// The `--upgrade` option tells `pip` to upgrade the packages if they are already installed. diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index c294ef88d..53fc851f1 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -213,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 4. 要件ファイルにあるパッケージの依存関係をインストールします `--no-cache-dir` オプションはダウンロードしたパッケージをローカルに保存しないように `pip` に指示します。これは、同じパッケージをインストールするために `pip` を再度実行する場合にのみ有効ですが、コンテナで作業する場合はそうではないです。 - !!! note - `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + /// note + + `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + + /// `--upgrade` オプションは、パッケージが既にインストールされている場合、`pip` にアップグレードするように指示します。 diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index edf10b318..502a36fc0 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. - !!! note "노트" - `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + /// note | 노트 + + `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + + /// `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md index 7c3b15d33..932952b4a 100644 --- a/docs/ko/docs/help-fastapi.md +++ b/docs/ko/docs/help-fastapi.md @@ -118,7 +118,11 @@ 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. - !!! tip 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + /// tip + + 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + + /// ``` 다른 일반적인 대화에서만 채팅을 사용하십시오. diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index fa1a6b9c2..df93bac2c 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -205,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] A opção `--no-cache-dir` diz ao `pip` para não salvar os pacotes baixados localmente, pois isso só aconteceria se `pip` fosse executado novamente para instalar os mesmos pacotes, mas esse não é o caso quando trabalhamos com contêineres. - !!! note - `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + /// note + + `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + + /// A opção `--upgrade` diz ao `pip` para atualizar os pacotes se eles já estiverem instalados. diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index e627d01fe..9eef5c4d2 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -207,8 +207,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Опция `--no-cache-dir` указывает `pip` не сохранять загружаемые библиотеки на локальной машине для использования их в случае повторной загрузки. В контейнере, в случае пересборки этого шага, они всё равно будут удалены. - !!! note "Заметка" - Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + /// note | Заметка + + Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + + /// Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index e5f66dba1..f120ebfb8 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -213,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 - !!! note "笔记" - `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + /// note | 笔记 + + `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + + /// `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index e5d66482a..9c963d587 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -4,8 +4,11 @@ 但实际情况比这复杂得多。 -!!!提示 - 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 +/// note | 提示 + +如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +/// 要从用户的视角**了解 HTTPS 的基础知识**,请查看 https://howhttps.works/。 From d839e3ccbbcaa771a5ce2b925a1916939556aa21 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 12 Aug 2024 21:48:16 +0000 Subject: [PATCH 036/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c861508b4..d7af1ccb6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo). From 922ce32aa2a6cc4e78e8bcaa0a781d13060e4863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 18:04:54 -0500 Subject: [PATCH 037/356] =?UTF-8?q?=F0=9F=91=B7=20Add=20GitHub=20Action=20?= =?UTF-8?q?add-to-project=20(#11999)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/add-to-project.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/add-to-project.yml diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml new file mode 100644 index 000000000..701f06fae --- /dev/null +++ b/.github/workflows/add-to-project.yml @@ -0,0 +1,22 @@ +name: Add to Project + +on: + pull_request: + types: + - opened + - reopened + - synchronize + issues: + types: + - opened + - reopened + +jobs: + add-to-project: + name: Add to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v1.0.2 + with: + project-url: https://github.com/orgs/fastapi/projects/2 + github-token: ${{ secrets.PROJECTS_TOKEN }} From 768df2736ec57c3e54201485d4e962db7dd762c4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 12 Aug 2024 23:05:15 +0000 Subject: [PATCH 038/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7af1ccb6..84efe6bc0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo). From 748159289f438d39ce424681c3ccd2d694561ca4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 20:02:29 -0500 Subject: [PATCH 039/356] =?UTF-8?q?=F0=9F=91=B7=20Add=20GitHub=20Action=20?= =?UTF-8?q?labeler=20(#12000)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 23 +++++++++++++++++++++++ .github/workflows/labeler.yml | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 .github/labeler.yml create mode 100644 .github/workflows/labeler.yml diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..e07a303b1 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,23 @@ +docs: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/* + - docs_src/* + +lang-all: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/*/docs/* + - all-globs-to-all-files: + - '!docs/en/docs/*' + +internal: + - changed-files: + - any-glob-to-any-file: + - .github/* + - scripts/* + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..9cbdfda21 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,12 @@ +name: Pull Request Labeler +on: + pull_request_target: + +jobs: + labeler: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 From 663810cb1a2e770ffc885365a17a6244df3967f1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 13 Aug 2024 01:02:50 +0000 Subject: [PATCH 040/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 84efe6bc0..d3fa9aa40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo). From b5e167d406f2d08caa02e0672a8a2f291053fee6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 20:47:59 -0500 Subject: [PATCH 041/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20labeler=20GitHu?= =?UTF-8?q?b=20Action=20(#12001)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index e07a303b1..758f37e37 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,22 +1,22 @@ docs: - changed-files: - any-glob-to-any-file: - - docs/en/docs/* - - docs_src/* + - docs/en/docs/**/* + - docs_src/**/* lang-all: - all: - changed-files: - any-glob-to-any-file: - - docs/*/docs/* + - docs/*/docs/**/* - all-globs-to-all-files: - - '!docs/en/docs/*' + - '!docs/en/docs/**/*' internal: - changed-files: - any-glob-to-any-file: - - .github/* - - scripts/* + - .github/**/* + - scripts/**/* - .gitignore - .pre-commit-config.yaml - pdm_build.py From 14779a3ae141f56869d845616b03cc9b77f1365a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 13 Aug 2024 01:48:24 +0000 Subject: [PATCH 042/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d3fa9aa40..7e1c49eaa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). * 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo). From 48c269ba6820c5a7c39af91f9462d93b2940353c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 21:00:25 -0500 Subject: [PATCH 043/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?=20add-to-project=20(#12002)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/add-to-project.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml index 701f06fae..dccea83f3 100644 --- a/.github/workflows/add-to-project.yml +++ b/.github/workflows/add-to-project.yml @@ -1,11 +1,7 @@ name: Add to Project on: - pull_request: - types: - - opened - - reopened - - synchronize + pull_request_target: issues: types: - opened From 14c621ea3013df983144aa4fdf9fdb4fcdbbe64c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 13 Aug 2024 02:00:51 +0000 Subject: [PATCH 044/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7e1c49eaa..2f2727797 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo). From c89533254ec58785dc9f6ea0489372bafb3e8089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 12 Aug 2024 23:54:14 -0500 Subject: [PATCH 045/356] =?UTF-8?q?=F0=9F=91=B7=20Add=20label=20checker=20?= =?UTF-8?q?GitHub=20Action=20(#12004)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-checker.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/label-checker.yml diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml new file mode 100644 index 000000000..20e9704cb --- /dev/null +++ b/.github/workflows/label-checker.yml @@ -0,0 +1,19 @@ +name: Label Checker +on: + pull_request: + types: + - opened + - synchronize + - reopened + - labeled + - unlabeled + +jobs: + check_labels: + name: Check labels + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} From 26a37a6a2043ea76d3a62df7688e64eda6ee8bd1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 13 Aug 2024 04:54:36 +0000 Subject: [PATCH 046/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f2727797..f3782805e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). * 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo). From e5f25e3bcaa329834d0b7c8236c6307aca3ef66c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 13 Aug 2024 00:39:57 -0500 Subject: [PATCH 047/356] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Add=20GitHub?= =?UTF-8?q?=20Action=20label-checker=20(#12005)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/labeler.yml | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 9cbdfda21..7cb88936b 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,6 +1,13 @@ -name: Pull Request Labeler +name: Pull Request Labeler and Checker on: pull_request_target: + types: + - opened + - synchronize + - reopened + # For label-checker + - labeled + - unlabeled jobs: labeler: @@ -10,3 +17,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 + # Run this after labeler applied labels + check-labels: + name: Check labels + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} From 69a6456d9e3729eaefd7ba9a0196916909c0ed2a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 13 Aug 2024 05:40:18 +0000 Subject: [PATCH 048/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3782805e..90ef1452d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo). From 7c6e70a0c73ab0c32335c03070eb9a2d9b944944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 13 Aug 2024 19:30:46 -0500 Subject: [PATCH 049/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20permissions=20a?= =?UTF-8?q?nd=20config=20for=20labeler=20GitHub=20Action=20(#12008)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-checker.yml | 19 ------------------- .github/workflows/labeler.yml | 4 ++++ 2 files changed, 4 insertions(+), 19 deletions(-) delete mode 100644 .github/workflows/label-checker.yml diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml deleted file mode 100644 index 20e9704cb..000000000 --- a/.github/workflows/label-checker.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Label Checker -on: - pull_request: - types: - - opened - - synchronize - - reopened - - labeled - - unlabeled - -jobs: - check_labels: - name: Check labels - runs-on: ubuntu-latest - steps: - - uses: docker://agilepathway/pull-request-label-checker:latest - with: - one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal - repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 7cb88936b..7c5b4616a 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -19,6 +19,10 @@ jobs: - uses: actions/labeler@v5 # Run this after labeler applied labels check-labels: + needs: + - labeler + permissions: + pull-requests: read name: Check labels runs-on: ubuntu-latest steps: From 96cb538fa3621b7be283f4209e675327a0c1fe92 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 14 Aug 2024 00:31:10 +0000 Subject: [PATCH 050/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 90ef1452d..99c1507f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). * 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo). From 2dad7c98344f05dadd5cb198a5c5e2f9b166162f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 14 Aug 2024 09:33:27 -0500 Subject: [PATCH 051/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20configs=20for?= =?UTF-8?q?=20MkDocs=20for=20languages=20and=20social=20cards=20(#12016)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/layouts/custom.yml | 228 ------------------------------------ docs/en/mkdocs.insiders.yml | 2 - docs/en/mkdocs.yml | 3 +- 3 files changed, 2 insertions(+), 231 deletions(-) delete mode 100644 docs/en/layouts/custom.yml diff --git a/docs/en/layouts/custom.yml b/docs/en/layouts/custom.yml deleted file mode 100644 index aad81af28..000000000 --- a/docs/en/layouts/custom.yml +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) 2016-2023 Martin Donath - -# 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 NON-INFRINGEMENT. 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. - -# ----------------------------------------------------------------------------- -# Configuration -# ----------------------------------------------------------------------------- - -# The same default card with a a configurable logo - -# Definitions -definitions: - - # Background image - - &background_image >- - {{ layout.background_image or "" }} - - # Background color (default: indigo) - - &background_color >- - {%- if layout.background_color -%} - {{ layout.background_color }} - {%- else -%} - {%- set palette = config.theme.palette or {} -%} - {%- if not palette is mapping -%} - {%- set palette = palette | first -%} - {%- endif -%} - {%- set primary = palette.get("primary", "indigo") -%} - {%- set primary = primary.replace(" ", "-") -%} - {{ { - "red": "#ef5552", - "pink": "#e92063", - "purple": "#ab47bd", - "deep-purple": "#7e56c2", - "indigo": "#4051b5", - "blue": "#2094f3", - "light-blue": "#02a6f2", - "cyan": "#00bdd6", - "teal": "#009485", - "green": "#4cae4f", - "light-green": "#8bc34b", - "lime": "#cbdc38", - "yellow": "#ffec3d", - "amber": "#ffc105", - "orange": "#ffa724", - "deep-orange": "#ff6e42", - "brown": "#795649", - "grey": "#757575", - "blue-grey": "#546d78", - "black": "#000000", - "white": "#ffffff" - }[primary] or "#4051b5" }} - {%- endif -%} - - # Text color (default: white) - - &color >- - {%- if layout.color -%} - {{ layout.color }} - {%- else -%} - {%- set palette = config.theme.palette or {} -%} - {%- if not palette is mapping -%} - {%- set palette = palette | first -%} - {%- endif -%} - {%- set primary = palette.get("primary", "indigo") -%} - {%- set primary = primary.replace(" ", "-") -%} - {{ { - "red": "#ffffff", - "pink": "#ffffff", - "purple": "#ffffff", - "deep-purple": "#ffffff", - "indigo": "#ffffff", - "blue": "#ffffff", - "light-blue": "#ffffff", - "cyan": "#ffffff", - "teal": "#ffffff", - "green": "#ffffff", - "light-green": "#ffffff", - "lime": "#000000", - "yellow": "#000000", - "amber": "#000000", - "orange": "#000000", - "deep-orange": "#ffffff", - "brown": "#ffffff", - "grey": "#ffffff", - "blue-grey": "#ffffff", - "black": "#ffffff", - "white": "#000000" - }[primary] or "#ffffff" }} - {%- endif -%} - - # Font family (default: Roboto) - - &font_family >- - {%- if layout.font_family -%} - {{ layout.font_family }} - {%- elif config.theme.font != false -%} - {{ config.theme.font.get("text", "Roboto") }} - {%- else -%} - Roboto - {%- endif -%} - - # Site name - - &site_name >- - {{ config.site_name }} - - # Page title - - &page_title >- - {{ page.meta.get("title", page.title) }} - - # Page title with site name - - &page_title_with_site_name >- - {%- if not page.is_homepage -%} - {{ page.meta.get("title", page.title) }} - {{ config.site_name }} - {%- else -%} - {{ page.meta.get("title", page.title) }} - {%- endif -%} - - # Page description - - &page_description >- - {{ page.meta.get("description", config.site_description) or "" }} - - - # Start of custom modified logic - # Logo - - &logo >- - {%- if layout.logo -%} - {{ layout.logo }} - {%- elif config.theme.logo -%} - {{ config.docs_dir }}/{{ config.theme.logo }} - {%- endif -%} - # End of custom modified logic - - # Logo (icon) - - &logo_icon >- - {{ config.theme.icon.logo or "" }} - -# Meta tags -tags: - - # Open Graph - og:type: website - og:title: *page_title_with_site_name - og:description: *page_description - og:image: "{{ image.url }}" - og:image:type: "{{ image.type }}" - og:image:width: "{{ image.width }}" - og:image:height: "{{ image.height }}" - og:url: "{{ page.canonical_url }}" - - # Twitter - twitter:card: summary_large_image - twitter.title: *page_title_with_site_name - twitter:description: *page_description - twitter:image: "{{ image.url }}" - -# ----------------------------------------------------------------------------- -# Specification -# ----------------------------------------------------------------------------- - -# Card size and layers -size: { width: 1200, height: 630 } -layers: - - # Background - - background: - image: *background_image - color: *background_color - - # Logo - - size: { width: 144, height: 144 } - offset: { x: 992, y: 64 } - background: - image: *logo - icon: - value: *logo_icon - color: *color - - # Site name - - size: { width: 832, height: 42 } - offset: { x: 64, y: 64 } - typography: - content: *site_name - color: *color - font: - family: *font_family - style: Bold - - # Page title - - size: { width: 832, height: 310 } - offset: { x: 62, y: 160 } - typography: - content: *page_title - align: start - color: *color - line: - amount: 3 - height: 1.25 - font: - family: *font_family - style: Bold - - # Page description - - size: { width: 832, height: 64 } - offset: { x: 64, y: 512 } - typography: - content: *page_description - align: start - color: *color - line: - amount: 2 - height: 1.5 - font: - family: *font_family - style: Regular diff --git a/docs/en/mkdocs.insiders.yml b/docs/en/mkdocs.insiders.yml index 4cec588fa..8d6d26e17 100644 --- a/docs/en/mkdocs.insiders.yml +++ b/docs/en/mkdocs.insiders.yml @@ -1,7 +1,5 @@ plugins: social: - cards_layout_dir: ../en/layouts - cards_layout: custom cards_layout_options: logo: ../en/docs/img/icon-white.svg typeset: diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d37d7f42f..d23ddd42f 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -57,7 +57,8 @@ repo_url: https://github.com/fastapi/fastapi plugins: # Material for MkDocs search: - social: + # Configured in mkdocs.insiders.yml + # social: # Other plugins macros: include_yaml: From 4c490de33d351df15907b124e5aafddaaac75d94 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 14 Aug 2024 14:33:49 +0000 Subject: [PATCH 052/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 99c1507f8..8637e4643 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). * 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo). From 9f57ecd41fde086427f7cbf75d6f1e94d4d58d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 14 Aug 2024 13:29:24 -0500 Subject: [PATCH 053/356] =?UTF-8?q?=F0=9F=91=B7=F0=9F=8F=BB=20Update=20Lab?= =?UTF-8?q?eler=20GitHub=20Actions=20(#12019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 39 ++++++++++++++++++++++------------- .github/workflows/labeler.yml | 5 +++-- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index 758f37e37..1d49a2411 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,23 +1,34 @@ docs: - - changed-files: - - any-glob-to-any-file: - - docs/en/docs/**/* - - docs_src/**/* + - all: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/** + - docs_src/** + - all-globs-to-all-files: + - '!fastapi/**' + - '!pyproject.toml' lang-all: - all: - changed-files: - any-glob-to-any-file: - - docs/*/docs/**/* + - docs/*/docs/** - all-globs-to-all-files: - - '!docs/en/docs/**/*' + - '!docs/en/docs/**' + - '!fastapi/**' + - '!pyproject.toml' internal: - - changed-files: - - any-glob-to-any-file: - - .github/**/* - - scripts/**/* - - .gitignore - - .pre-commit-config.yaml - - pdm_build.py - - requirements*.txt + - all: + - changed-files: + - any-glob-to-any-file: + - .github/** + - scripts/** + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt + - all-globs-to-all-files: + - '!docs/*/docs/**' + - '!fastapi/**' + - '!pyproject.toml' diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 7c5b4616a..d62f1668d 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,4 +1,4 @@ -name: Pull Request Labeler and Checker +name: Labels on: pull_request_target: types: @@ -17,13 +17,14 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 + with: + sync-labels: true # Run this after labeler applied labels check-labels: needs: - labeler permissions: pull-requests: read - name: Check labels runs-on: ubuntu-latest steps: - uses: docker://agilepathway/pull-request-label-checker:latest From 75705617a66300847436e39ba703af1b8d109963 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 14 Aug 2024 18:29:51 +0000 Subject: [PATCH 054/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8637e4643..2685396a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo). From 85bd4067c2133a9eac1cec30b2c7d39aa67f4fc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 14 Aug 2024 17:57:10 -0500 Subject: [PATCH 055/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20documentation=20fo?= =?UTF-8?q?r=20non-translated=20pages=20and=20scripts=20to=20verify=20them?= =?UTF-8?q?=20(#12020)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/external-links.md | 42 ------ docs/de/docs/newsletter.md | 5 - docs/de/docs/reference/apirouter.md | 24 ---- docs/de/docs/reference/background.md | 11 -- docs/de/docs/reference/dependencies.md | 29 ---- docs/de/docs/reference/encoders.md | 3 - docs/de/docs/reference/exceptions.md | 20 --- docs/de/docs/reference/fastapi.md | 31 ----- docs/de/docs/reference/httpconnection.md | 11 -- docs/de/docs/reference/index.md | 11 -- docs/de/docs/reference/middleware.md | 45 ------- docs/de/docs/reference/openapi/docs.md | 11 -- docs/de/docs/reference/openapi/index.md | 5 - docs/de/docs/reference/openapi/models.md | 5 - docs/de/docs/reference/parameters.md | 35 ----- docs/de/docs/reference/request.md | 17 --- docs/de/docs/reference/response.md | 13 -- docs/de/docs/reference/responses.md | 164 ----------------------- docs/de/docs/reference/security/index.md | 73 ---------- docs/de/docs/reference/staticfiles.md | 13 -- docs/de/docs/reference/status.md | 36 ----- docs/de/docs/reference/templating.md | 13 -- docs/de/docs/reference/testclient.md | 13 -- docs/de/docs/reference/uploadfile.md | 22 --- docs/de/docs/reference/websockets.md | 67 --------- docs/em/docs/external-links.md | 38 ------ docs/en/docs/contributing.md | 16 +++ docs/es/docs/external-links.md | 36 ----- docs/es/docs/newsletter.md | 5 - docs/fr/docs/external-links.md | 36 ----- docs/ja/docs/external-links.md | 36 ----- docs/pt/docs/external-links.md | 36 ----- docs/pt/docs/reference/apirouter.md | 24 ---- docs/pt/docs/reference/background.md | 11 -- docs/pt/docs/reference/exceptions.md | 20 --- docs/pt/docs/reference/index.md | 6 - docs/ru/docs/external-links.md | 36 ----- docs/tr/docs/external-links.md | 36 ----- docs/tr/docs/newsletter.md | 5 - scripts/docs.py | 33 +++++ scripts/mkdocs_hooks.py | 8 +- 41 files changed, 55 insertions(+), 1046 deletions(-) delete mode 100644 docs/de/docs/external-links.md delete mode 100644 docs/de/docs/newsletter.md delete mode 100644 docs/de/docs/reference/apirouter.md delete mode 100644 docs/de/docs/reference/background.md delete mode 100644 docs/de/docs/reference/dependencies.md delete mode 100644 docs/de/docs/reference/encoders.md delete mode 100644 docs/de/docs/reference/exceptions.md delete mode 100644 docs/de/docs/reference/fastapi.md delete mode 100644 docs/de/docs/reference/httpconnection.md delete mode 100644 docs/de/docs/reference/index.md delete mode 100644 docs/de/docs/reference/middleware.md delete mode 100644 docs/de/docs/reference/openapi/docs.md delete mode 100644 docs/de/docs/reference/openapi/index.md delete mode 100644 docs/de/docs/reference/openapi/models.md delete mode 100644 docs/de/docs/reference/parameters.md delete mode 100644 docs/de/docs/reference/request.md delete mode 100644 docs/de/docs/reference/response.md delete mode 100644 docs/de/docs/reference/responses.md delete mode 100644 docs/de/docs/reference/security/index.md delete mode 100644 docs/de/docs/reference/staticfiles.md delete mode 100644 docs/de/docs/reference/status.md delete mode 100644 docs/de/docs/reference/templating.md delete mode 100644 docs/de/docs/reference/testclient.md delete mode 100644 docs/de/docs/reference/uploadfile.md delete mode 100644 docs/de/docs/reference/websockets.md delete mode 100644 docs/em/docs/external-links.md delete mode 100644 docs/es/docs/external-links.md delete mode 100644 docs/es/docs/newsletter.md delete mode 100644 docs/fr/docs/external-links.md delete mode 100644 docs/ja/docs/external-links.md delete mode 100644 docs/pt/docs/external-links.md delete mode 100644 docs/pt/docs/reference/apirouter.md delete mode 100644 docs/pt/docs/reference/background.md delete mode 100644 docs/pt/docs/reference/exceptions.md delete mode 100644 docs/pt/docs/reference/index.md delete mode 100644 docs/ru/docs/external-links.md delete mode 100644 docs/tr/docs/external-links.md delete mode 100644 docs/tr/docs/newsletter.md diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md deleted file mode 100644 index ae5a6c908..000000000 --- a/docs/de/docs/external-links.md +++ /dev/null @@ -1,42 +0,0 @@ -# Externe Links und Artikel - -**FastAPI** hat eine großartige Community, die ständig wächst. - -Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. - -Hier ist eine unvollständige Liste einiger davon. - -/// tip | "Tipp" - -Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen Pull Request und fügen Sie es hinzu. - -/// - -/// note | "Hinweis Deutsche Übersetzung" - -Die folgenden Überschriften und Links werden aus einer anderen Datei gelesen und sind daher nicht ins Deutsche übersetzt. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projekte - -Die neuesten GitHub-Projekte zum Thema `fastapi`: - -
-
diff --git a/docs/de/docs/newsletter.md b/docs/de/docs/newsletter.md deleted file mode 100644 index 31995b164..000000000 --- a/docs/de/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI und Freunde Newsletter - - - - diff --git a/docs/de/docs/reference/apirouter.md b/docs/de/docs/reference/apirouter.md deleted file mode 100644 index b0728b7df..000000000 --- a/docs/de/docs/reference/apirouter.md +++ /dev/null @@ -1,24 +0,0 @@ -# `APIRouter`-Klasse - -Hier sind die Referenzinformationen für die Klasse `APIRouter` mit all ihren Parametern, Attributen und Methoden. - -Sie können die `APIRouter`-Klasse direkt von `fastapi` importieren: - -```python -from fastapi import APIRouter -``` - -::: fastapi.APIRouter - options: - members: - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event diff --git a/docs/de/docs/reference/background.md b/docs/de/docs/reference/background.md deleted file mode 100644 index 0fd389325..000000000 --- a/docs/de/docs/reference/background.md +++ /dev/null @@ -1,11 +0,0 @@ -# Hintergrundtasks – `BackgroundTasks` - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeitsfunktion mit dem Typ `BackgroundTasks` deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren. - -Sie können `BackgroundTasks` direkt von `fastapi` importieren: - -```python -from fastapi import BackgroundTasks -``` - -::: fastapi.BackgroundTasks diff --git a/docs/de/docs/reference/dependencies.md b/docs/de/docs/reference/dependencies.md deleted file mode 100644 index 2ed5b5050..000000000 --- a/docs/de/docs/reference/dependencies.md +++ /dev/null @@ -1,29 +0,0 @@ -# Abhängigkeiten – `Depends()` und `Security()` - -## `Depends()` - -Abhängigkeiten werden hauptsächlich mit der speziellen Funktion `Depends()` behandelt, die ein Callable entgegennimmt. - -Hier finden Sie deren Referenz und Parameter. - -Sie können sie direkt von `fastapi` importieren: - -```python -from fastapi import Depends -``` - -::: fastapi.Depends - -## `Security()` - -In vielen Szenarien können Sie die Sicherheit (Autorisierung, Authentifizierung usw.) mit Abhängigkeiten handhaben, indem Sie `Depends()` verwenden. - -Wenn Sie jedoch auch OAuth2-Scopes deklarieren möchten, können Sie `Security()` anstelle von `Depends()` verwenden. - -Sie können `Security()` direkt von `fastapi` importieren: - -```python -from fastapi import Security -``` - -::: fastapi.Security diff --git a/docs/de/docs/reference/encoders.md b/docs/de/docs/reference/encoders.md deleted file mode 100644 index 2489b8c60..000000000 --- a/docs/de/docs/reference/encoders.md +++ /dev/null @@ -1,3 +0,0 @@ -# Encoder – `jsonable_encoder` - -::: fastapi.encoders.jsonable_encoder diff --git a/docs/de/docs/reference/exceptions.md b/docs/de/docs/reference/exceptions.md deleted file mode 100644 index 230f902a9..000000000 --- a/docs/de/docs/reference/exceptions.md +++ /dev/null @@ -1,20 +0,0 @@ -# Exceptions – `HTTPException` und `WebSocketException` - -Dies sind die Exceptions, die Sie auslösen können, um dem Client Fehler zu berichten. - -Wenn Sie eine Exception auslösen, wird, wie es bei normalem Python der Fall wäre, der Rest der Ausführung abgebrochen. Auf diese Weise können Sie diese Exceptions von überall im Code werfen, um einen Request abzubrechen und den Fehler dem Client anzuzeigen. - -Sie können Folgendes verwenden: - -* `HTTPException` -* `WebSocketException` - -Diese Exceptions können direkt von `fastapi` importiert werden: - -```python -from fastapi import HTTPException, WebSocketException -``` - -::: fastapi.HTTPException - -::: fastapi.WebSocketException diff --git a/docs/de/docs/reference/fastapi.md b/docs/de/docs/reference/fastapi.md deleted file mode 100644 index 4e6a56971..000000000 --- a/docs/de/docs/reference/fastapi.md +++ /dev/null @@ -1,31 +0,0 @@ -# `FastAPI`-Klasse - -Hier sind die Referenzinformationen für die Klasse `FastAPI` mit all ihren Parametern, Attributen und Methoden. - -Sie können die `FastAPI`-Klasse direkt von `fastapi` importieren: - -```python -from fastapi import FastAPI -``` - -::: fastapi.FastAPI - options: - members: - - openapi_version - - webhooks - - state - - dependency_overrides - - openapi - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event - - middleware - - exception_handler diff --git a/docs/de/docs/reference/httpconnection.md b/docs/de/docs/reference/httpconnection.md deleted file mode 100644 index 32a9696fa..000000000 --- a/docs/de/docs/reference/httpconnection.md +++ /dev/null @@ -1,11 +0,0 @@ -# `HTTPConnection`-Klasse - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -Sie können diese von `fastapi.requests` importieren: - -```python -from fastapi.requests import HTTPConnection -``` - -::: fastapi.requests.HTTPConnection diff --git a/docs/de/docs/reference/index.md b/docs/de/docs/reference/index.md deleted file mode 100644 index 6fd0ef15f..000000000 --- a/docs/de/docs/reference/index.md +++ /dev/null @@ -1,11 +0,0 @@ -# Referenz – Code-API - -Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können. - -Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen. - -/// note | "Hinweis Deutsche Übersetzung" - -Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch. - -/// diff --git a/docs/de/docs/reference/middleware.md b/docs/de/docs/reference/middleware.md deleted file mode 100644 index d8d2d50fc..000000000 --- a/docs/de/docs/reference/middleware.md +++ /dev/null @@ -1,45 +0,0 @@ -# Middleware - -Es gibt mehrere Middlewares, die direkt von Starlette bereitgestellt werden. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Middleware](../advanced/middleware.md). - -::: fastapi.middleware.cors.CORSMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.cors import CORSMiddleware -``` - -::: fastapi.middleware.gzip.GZipMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.gzip import GZipMiddleware -``` - -::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware -``` - -::: fastapi.middleware.trustedhost.TrustedHostMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.trustedhost import TrustedHostMiddleware -``` - -::: fastapi.middleware.wsgi.WSGIMiddleware - -Kann von `fastapi` importiert werden: - -```python -from fastapi.middleware.wsgi import WSGIMiddleware -``` diff --git a/docs/de/docs/reference/openapi/docs.md b/docs/de/docs/reference/openapi/docs.md deleted file mode 100644 index 3c19ba917..000000000 --- a/docs/de/docs/reference/openapi/docs.md +++ /dev/null @@ -1,11 +0,0 @@ -# OpenAPI `docs` - -Werkzeuge zur Verwaltung der automatischen OpenAPI-UI-Dokumentation, einschließlich Swagger UI (standardmäßig unter `/docs`) und ReDoc (standardmäßig unter `/redoc`). - -::: fastapi.openapi.docs.get_swagger_ui_html - -::: fastapi.openapi.docs.get_redoc_html - -::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html - -::: fastapi.openapi.docs.swagger_ui_default_parameters diff --git a/docs/de/docs/reference/openapi/index.md b/docs/de/docs/reference/openapi/index.md deleted file mode 100644 index 0ae3d67c6..000000000 --- a/docs/de/docs/reference/openapi/index.md +++ /dev/null @@ -1,5 +0,0 @@ -# OpenAPI - -Es gibt mehrere Werkzeuge zur Handhabung von OpenAPI. - -Normalerweise müssen Sie diese nicht verwenden, es sei denn, Sie haben einen bestimmten fortgeschrittenen Anwendungsfall, welcher das erfordert. diff --git a/docs/de/docs/reference/openapi/models.md b/docs/de/docs/reference/openapi/models.md deleted file mode 100644 index 64306b15f..000000000 --- a/docs/de/docs/reference/openapi/models.md +++ /dev/null @@ -1,5 +0,0 @@ -# OpenAPI-`models` - -OpenAPI Pydantic-Modelle, werden zum Generieren und Validieren der generierten OpenAPI verwendet. - -::: fastapi.openapi.models diff --git a/docs/de/docs/reference/parameters.md b/docs/de/docs/reference/parameters.md deleted file mode 100644 index 2638eaf48..000000000 --- a/docs/de/docs/reference/parameters.md +++ /dev/null @@ -1,35 +0,0 @@ -# Request-Parameter - -Hier die Referenzinformationen für die Request-Parameter. - -Dies sind die Sonderfunktionen, die Sie mittels `Annotated` in *Pfadoperation-Funktion*-Parameter oder Abhängigkeitsfunktionen einfügen können, um Daten aus dem Request abzurufen. - -Dies beinhaltet: - -* `Query()` -* `Path()` -* `Body()` -* `Cookie()` -* `Header()` -* `Form()` -* `File()` - -Sie können diese alle direkt von `fastapi` importieren: - -```python -from fastapi import Body, Cookie, File, Form, Header, Path, Query -``` - -::: fastapi.Query - -::: fastapi.Path - -::: fastapi.Body - -::: fastapi.Cookie - -::: fastapi.Header - -::: fastapi.Form - -::: fastapi.File diff --git a/docs/de/docs/reference/request.md b/docs/de/docs/reference/request.md deleted file mode 100644 index cf7eb61ad..000000000 --- a/docs/de/docs/reference/request.md +++ /dev/null @@ -1,17 +0,0 @@ -# `Request`-Klasse - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als vom Typ `Request` deklarieren und dann direkt auf das Requestobjekt zugreifen, ohne jegliche Validierung, usw. - -Sie können es direkt von `fastapi` importieren: - -```python -from fastapi import Request -``` - -/// tip | "Tipp" - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -/// - -::: fastapi.Request diff --git a/docs/de/docs/reference/response.md b/docs/de/docs/reference/response.md deleted file mode 100644 index 215918931..000000000 --- a/docs/de/docs/reference/response.md +++ /dev/null @@ -1,13 +0,0 @@ -# `Response`-Klasse - -Sie können einen Parameter in einer *Pfadoperation-Funktion* oder einer Abhängigkeit als `Response` deklarieren und dann Daten für die Response wie Header oder Cookies festlegen. - -Diese können Sie auch direkt verwenden, um eine Instanz davon zu erstellen und diese von Ihren *Pfadoperationen* zurückzugeben. - -Sie können sie direkt von `fastapi` importieren: - -```python -from fastapi import Response -``` - -::: fastapi.Response diff --git a/docs/de/docs/reference/responses.md b/docs/de/docs/reference/responses.md deleted file mode 100644 index c0e9f07e7..000000000 --- a/docs/de/docs/reference/responses.md +++ /dev/null @@ -1,164 +0,0 @@ -# Benutzerdefinierte Responseklassen – File, HTML, Redirect, Streaming, usw. - -Es gibt mehrere benutzerdefinierte Responseklassen, von denen Sie eine Instanz erstellen und diese direkt von Ihren *Pfadoperationen* zurückgeben können. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu benutzerdefinierten Responses – HTML, Stream, Datei, andere](../advanced/custom-response.md). - -Sie können diese direkt von `fastapi.responses` importieren: - -```python -from fastapi.responses import ( - FileResponse, - HTMLResponse, - JSONResponse, - ORJSONResponse, - PlainTextResponse, - RedirectResponse, - Response, - StreamingResponse, - UJSONResponse, -) -``` - -## FastAPI-Responses - -Es gibt einige benutzerdefinierte FastAPI-Responseklassen, welche Sie verwenden können, um die JSON-Performanz zu optimieren. - -::: fastapi.responses.UJSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.ORJSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -## Starlette-Responses - -::: fastapi.responses.FileResponse - options: - members: - - chunk_size - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.HTMLResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.JSONResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.PlainTextResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.RedirectResponse - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.Response - options: - members: - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie - -::: fastapi.responses.StreamingResponse - options: - members: - - body_iterator - - charset - - status_code - - media_type - - body - - background - - raw_headers - - render - - init_headers - - headers - - set_cookie - - delete_cookie diff --git a/docs/de/docs/reference/security/index.md b/docs/de/docs/reference/security/index.md deleted file mode 100644 index 4c2375f2f..000000000 --- a/docs/de/docs/reference/security/index.md +++ /dev/null @@ -1,73 +0,0 @@ -# Sicherheitstools - -Wenn Sie Abhängigkeiten mit OAuth2-Scopes deklarieren müssen, verwenden Sie `Security()`. - -Aber Sie müssen immer noch definieren, was das Dependable, das Callable ist, welches Sie als Parameter an `Depends()` oder `Security()` übergeben. - -Es gibt mehrere Tools, mit denen Sie diese Dependables erstellen können, und sie werden in OpenAPI integriert, sodass sie in der Oberfläche der automatischen Dokumentation angezeigt werden und von automatisch generierten Clients und SDKs, usw., verwendet werden können. - -Sie können sie von `fastapi.security` importieren: - -```python -from fastapi.security import ( - APIKeyCookie, - APIKeyHeader, - APIKeyQuery, - HTTPAuthorizationCredentials, - HTTPBasic, - HTTPBasicCredentials, - HTTPBearer, - HTTPDigest, - OAuth2, - OAuth2AuthorizationCodeBearer, - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - OAuth2PasswordRequestFormStrict, - OpenIdConnect, - SecurityScopes, -) -``` - -## API-Schlüssel-Sicherheitsschemas - -::: fastapi.security.APIKeyCookie - -::: fastapi.security.APIKeyHeader - -::: fastapi.security.APIKeyQuery - -## HTTP-Authentifizierungsschemas - -::: fastapi.security.HTTPBasic - -::: fastapi.security.HTTPBearer - -::: fastapi.security.HTTPDigest - -## HTTP-Anmeldeinformationen - -::: fastapi.security.HTTPAuthorizationCredentials - -::: fastapi.security.HTTPBasicCredentials - -## OAuth2-Authentifizierung - -::: fastapi.security.OAuth2 - -::: fastapi.security.OAuth2AuthorizationCodeBearer - -::: fastapi.security.OAuth2PasswordBearer - -## OAuth2-Passwortformulare - -::: fastapi.security.OAuth2PasswordRequestForm - -::: fastapi.security.OAuth2PasswordRequestFormStrict - -## OAuth2-Sicherheitsscopes in Abhängigkeiten - -::: fastapi.security.SecurityScopes - -## OpenID Connect - -::: fastapi.security.OpenIdConnect diff --git a/docs/de/docs/reference/staticfiles.md b/docs/de/docs/reference/staticfiles.md deleted file mode 100644 index 5629854c6..000000000 --- a/docs/de/docs/reference/staticfiles.md +++ /dev/null @@ -1,13 +0,0 @@ -# Statische Dateien – `StaticFiles` - -Sie können die `StaticFiles`-Klasse verwenden, um statische Dateien wie JavaScript, CSS, Bilder, usw. bereitzustellen. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu statischen Dateien](../tutorial/static-files.md). - -Sie können sie direkt von `fastapi.staticfiles` importieren: - -```python -from fastapi.staticfiles import StaticFiles -``` - -::: fastapi.staticfiles.StaticFiles diff --git a/docs/de/docs/reference/status.md b/docs/de/docs/reference/status.md deleted file mode 100644 index 1d9458ee9..000000000 --- a/docs/de/docs/reference/status.md +++ /dev/null @@ -1,36 +0,0 @@ -# Statuscodes - -Sie können das Modul `status` von `fastapi` importieren: - -```python -from fastapi import status -``` - -`status` wird direkt von Starlette bereitgestellt. - -Es enthält eine Gruppe benannter Konstanten (Variablen) mit ganzzahligen Statuscodes. - -Zum Beispiel: - -* 200: `status.HTTP_200_OK` -* 403: `status.HTTP_403_FORBIDDEN` -* usw. - -Es kann praktisch sein, schnell auf HTTP- (und WebSocket-)Statuscodes in Ihrer Anwendung zuzugreifen, indem Sie die automatische Vervollständigung für den Namen verwenden, ohne sich die Zahlen für die Statuscodes merken zu müssen. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Response-Statuscodes](../tutorial/response-status-code.md). - -## Beispiel - -```python -from fastapi import FastAPI, status - -app = FastAPI() - - -@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT) -def read_items(): - return [{"name": "Plumbus"}, {"name": "Portal Gun"}] -``` - -::: fastapi.status diff --git a/docs/de/docs/reference/templating.md b/docs/de/docs/reference/templating.md deleted file mode 100644 index c367a0179..000000000 --- a/docs/de/docs/reference/templating.md +++ /dev/null @@ -1,13 +0,0 @@ -# Templating – `Jinja2Templates` - -Sie können die `Jinja2Templates`-Klasse verwenden, um Jinja-Templates zu rendern. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation zu Templates](../advanced/templates.md). - -Sie können die Klasse direkt von `fastapi.templating` importieren: - -```python -from fastapi.templating import Jinja2Templates -``` - -::: fastapi.templating.Jinja2Templates diff --git a/docs/de/docs/reference/testclient.md b/docs/de/docs/reference/testclient.md deleted file mode 100644 index 5bc089c05..000000000 --- a/docs/de/docs/reference/testclient.md +++ /dev/null @@ -1,13 +0,0 @@ -# Testclient – `TestClient` - -Sie können die `TestClient`-Klasse verwenden, um FastAPI-Anwendungen zu testen, ohne eine tatsächliche HTTP- und Socket-Verbindung zu erstellen, Sie kommunizieren einfach direkt mit dem FastAPI-Code. - -Lesen Sie mehr darüber in der [FastAPI-Dokumentation über Testen](../tutorial/testing.md). - -Sie können sie direkt von `fastapi.testclient` importieren: - -```python -from fastapi.testclient import TestClient -``` - -::: fastapi.testclient.TestClient diff --git a/docs/de/docs/reference/uploadfile.md b/docs/de/docs/reference/uploadfile.md deleted file mode 100644 index 8556edf82..000000000 --- a/docs/de/docs/reference/uploadfile.md +++ /dev/null @@ -1,22 +0,0 @@ -# `UploadFile`-Klasse - -Sie können *Pfadoperation-Funktionsparameter* als Parameter vom Typ `UploadFile` definieren, um Dateien aus dem Request zu erhalten. - -Sie können es direkt von `fastapi` importieren: - -```python -from fastapi import UploadFile -``` - -::: fastapi.UploadFile - options: - members: - - file - - filename - - size - - headers - - content_type - - read - - write - - seek - - close diff --git a/docs/de/docs/reference/websockets.md b/docs/de/docs/reference/websockets.md deleted file mode 100644 index d5597d0ee..000000000 --- a/docs/de/docs/reference/websockets.md +++ /dev/null @@ -1,67 +0,0 @@ -# WebSockets - -Bei der Definition von WebSockets deklarieren Sie normalerweise einen Parameter vom Typ `WebSocket` und können damit Daten vom Client lesen und an ihn senden. Er wird direkt von Starlette bereitgestellt, Sie können ihn aber von `fastapi` importieren: - -```python -from fastapi import WebSocket -``` - -/// tip | "Tipp" - -Wenn Sie Abhängigkeiten definieren möchten, die sowohl mit HTTP als auch mit WebSockets kompatibel sein sollen, können Sie einen Parameter definieren, der eine `HTTPConnection` anstelle eines `Request` oder eines `WebSocket` akzeptiert. - -/// - -::: fastapi.WebSocket - options: - members: - - scope - - app - - url - - base_url - - headers - - query_params - - path_params - - cookies - - client - - state - - url_for - - client_state - - application_state - - receive - - send - - accept - - receive_text - - receive_bytes - - receive_json - - iter_text - - iter_bytes - - iter_json - - send_text - - send_bytes - - send_json - - close - -Wenn ein Client die Verbindung trennt, wird eine `WebSocketDisconnect`-Exception ausgelöst, die Sie abfangen können. - -Sie können diese direkt von `fastapi` importieren: - -```python -from fastapi import WebSocketDisconnect -``` - -::: fastapi.WebSocketDisconnect - -## WebSockets – zusätzliche Klassen - -Zusätzliche Klassen für die Handhabung von WebSockets. - -Werden direkt von Starlette bereitgestellt, Sie können sie jedoch von `fastapi` importieren: - -```python -from fastapi.websockets import WebSocketDisconnect, WebSocketState -``` - -::: fastapi.websockets.WebSocketDisconnect - -::: fastapi.websockets.WebSocketState diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md deleted file mode 100644 index 486b134d4..000000000 --- a/docs/em/docs/external-links.md +++ /dev/null @@ -1,38 +0,0 @@ -# 🔢 🔗 & 📄 - -**FastAPI** ✔️ 👑 👪 🕧 💗. - -📤 📚 🏤, 📄, 🧰, & 🏗, 🔗 **FastAPI**. - -📥 ❌ 📇 👫. - -/// tip - -🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ 🚲 📨 ❎ ⚫️. - -/// - -## 📄 - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## 🏗 - -⏪ 📂 🏗 ⏮️ ❔ `fastapi`: - -
-
diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 9d6b773f7..73d96e6e1 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -370,6 +370,22 @@ If you go to your browser you will see that now the docs show your new section ( Now you can translate it all and see how it looks as you save the file. +/// warning + +Don't translate: + +* Files under `reference/` +* `release-notes.md` +* `fastapi-people.md` +* `external-links.md` +* `newsletter.md` +* `management-tasks.md` +* `management.md` + +Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. + +/// + #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. diff --git a/docs/es/docs/external-links.md b/docs/es/docs/external-links.md deleted file mode 100644 index 8163349ab..000000000 --- a/docs/es/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Enlaces Externos y Artículos - -**FastAPI** tiene una gran comunidad en constante crecimiento. - -Hay muchas publicaciones, artículos, herramientas y proyectos relacionados con **FastAPI**. - -Aquí hay una lista incompleta de algunos de ellos. - -/// tip | "Consejo" - -Si tienes un artículo, proyecto, herramienta o cualquier cosa relacionada con **FastAPI** que aún no aparece aquí, crea un Pull Request agregándolo. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projects - -Últimos proyectos de GitHub con el tema `fastapi`: - -
-
diff --git a/docs/es/docs/newsletter.md b/docs/es/docs/newsletter.md deleted file mode 100644 index f4dcfe155..000000000 --- a/docs/es/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# Boletín de Noticias de FastAPI y amigos - - - - diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md deleted file mode 100644 index 91a9eae58..000000000 --- a/docs/fr/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Articles et liens externes - -**FastAPI** possède une grande communauté en constante extension. - -Il existe de nombreux articles, outils et projets liés à **FastAPI**. - -Voici une liste incomplète de certains d'entre eux. - -/// tip | "Astuce" - -Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projets - -Les projets Github avec le topic `fastapi` les plus récents : - -
-
diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md deleted file mode 100644 index 65cebc8d2..000000000 --- a/docs/ja/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# 外部リンク・記事 - -**FastAPI**には、絶えず成長している素晴らしいコミュニティがあります。 - -**FastAPI**に関連する投稿、記事、ツール、およびプロジェクトは多数あります。 - -それらの不完全なリストを以下に示します。 - -/// tip | "豆知識" - -ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## プロジェクト - -`fastapi`トピックの最新のGitHubプロジェクト: - -
-
diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md deleted file mode 100644 index 622ad5ab6..000000000 --- a/docs/pt/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Links externos e Artigos - -**FastAPI** tem uma grande comunidade em crescimento constante. - -Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **FastAPI**. - -Aqui tem uma lista, incompleta, de algumas delas. - -/// tip | "Dica" - -Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projetos - -Últimos projetos no GitHub com o tópico `fastapi`: - -
-
diff --git a/docs/pt/docs/reference/apirouter.md b/docs/pt/docs/reference/apirouter.md deleted file mode 100644 index 7568601c9..000000000 --- a/docs/pt/docs/reference/apirouter.md +++ /dev/null @@ -1,24 +0,0 @@ -# Classe `APIRouter` - -Aqui está a informação de referência para a classe `APIRouter`, com todos os seus parâmetros, atributos e métodos. - -Você pode importar a classe `APIRouter` diretamente do `fastapi`: - -```python -from fastapi import APIRouter -``` - -::: fastapi.APIRouter - options: - members: - - websocket - - include_router - - get - - put - - post - - delete - - options - - head - - patch - - trace - - on_event diff --git a/docs/pt/docs/reference/background.md b/docs/pt/docs/reference/background.md deleted file mode 100644 index bfc15aa76..000000000 --- a/docs/pt/docs/reference/background.md +++ /dev/null @@ -1,11 +0,0 @@ -# Tarefas em Segundo Plano - `BackgroundTasks` - -Você pode declarar um parâmetro em uma *função de operação de rota* ou em uma função de dependência com o tipo `BackgroundTasks`, e então utilizá-lo para agendar a execução de tarefas em segundo plano após o envio da resposta. - -Você pode importá-lo diretamente do `fastapi`: - -```python -from fastapi import BackgroundTasks -``` - -::: fastapi.BackgroundTasks diff --git a/docs/pt/docs/reference/exceptions.md b/docs/pt/docs/reference/exceptions.md deleted file mode 100644 index d6b5d2613..000000000 --- a/docs/pt/docs/reference/exceptions.md +++ /dev/null @@ -1,20 +0,0 @@ -# Exceções - `HTTPException` e `WebSocketException` - -Essas são as exceções que você pode lançar para mostrar erros ao cliente. - -Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente. - -Você pode usar: - -* `HTTPException` -* `WebSocketException` - -Essas exceções podem ser importadas diretamente do `fastapi`: - -```python -from fastapi import HTTPException, WebSocketException -``` - -::: fastapi.HTTPException - -::: fastapi.WebSocketException diff --git a/docs/pt/docs/reference/index.md b/docs/pt/docs/reference/index.md deleted file mode 100644 index 533a6a996..000000000 --- a/docs/pt/docs/reference/index.md +++ /dev/null @@ -1,6 +0,0 @@ -# Referência - API de Código - -Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações. - -Se você quer **aprender FastAPI**, é muito melhor ler o -[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/). diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md deleted file mode 100644 index 2c0e153e2..000000000 --- a/docs/ru/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Внешние ссылки и статьи - -**FastAPI** имеет отличное и постоянно растущее сообщество. - -Существует множество сообщений, статей, инструментов и проектов, связанных с **FastAPI**. - -Вот неполный список некоторых из них. - -/// tip - -Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Проекты - -Последние GitHub-проекты с пометкой `fastapi`: - -
-
diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md deleted file mode 100644 index 6e8af4025..000000000 --- a/docs/tr/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Harici Bağlantılar ve Makaleler - -**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. - -**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. - -Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. - -/// tip | "İpucu" - -Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. - -/// - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projeler - -`fastapi` konulu en son GitHub projeleri: - -
-
diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md deleted file mode 100644 index 22ca1b1e2..000000000 --- a/docs/tr/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI ve Arkadaşları Bülteni - - - - diff --git a/scripts/docs.py b/scripts/docs.py index 5ef548889..1dba4aa0a 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -26,6 +26,15 @@ missing_translation_snippet = """ {!../../../docs/missing-translation.md!} """ +non_translated_sections = [ + "reference/", + "release-notes.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", +] + docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name @@ -333,10 +342,34 @@ def verify_config() -> None: typer.echo("Valid mkdocs.yml ✅") +@app.command() +def verify_non_translated() -> None: + """ + Verify there are no files in the non translatable pages. + """ + print("Verifying non translated pages") + lang_paths = get_lang_paths() + error_paths = [] + for lang in lang_paths: + if lang.name == "en": + continue + for non_translatable in non_translated_sections: + non_translatable_path = lang / "docs" / non_translatable + if non_translatable_path.exists(): + error_paths.append(non_translatable_path) + if error_paths: + print("Non-translated pages found, remove them:") + for error_path in error_paths: + print(error_path) + raise typer.Abort() + print("No non-translated pages found ✅") + + @app.command() def verify_docs(): verify_readme() verify_config() + verify_non_translated() @app.command() diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 24ffecf46..10e8dc153 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -8,9 +8,13 @@ from mkdocs.structure.files import File, Files from mkdocs.structure.nav import Link, Navigation, Section from mkdocs.structure.pages import Page -non_traslated_sections = [ +non_translated_sections = [ "reference/", "release-notes.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", ] @@ -128,7 +132,7 @@ def on_page_markdown( markdown: str, *, page: Page, config: MkDocsConfig, files: Files ) -> str: if isinstance(page.file, EnFile): - for excluded_section in non_traslated_sections: + for excluded_section in non_translated_sections: if page.file.src_path.startswith(excluded_section): return markdown missing_translation_content = get_missing_translation_content(config.docs_dir) From 9c3845be8d42d08cc7ee8c8450adb8b41ca2e756 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 14 Aug 2024 22:57:35 +0000 Subject: [PATCH 056/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2685396a7..26dc7df89 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). ### Translations From c82497f78e38fd37cb214c5e0676e09fd1f70df7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 15 Aug 2024 10:21:25 -0500 Subject: [PATCH 057/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20section?= =?UTF-8?q?=20about=20"Don't=20Translate=20these=20Pages"=20(#12022)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/contributing.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 73d96e6e1..63e1f359a 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -370,9 +370,9 @@ If you go to your browser you will see that now the docs show your new section ( Now you can translate it all and see how it looks as you save the file. -/// warning +#### Don't Translate these Pages -Don't translate: +🚨 Don't translate: * Files under `reference/` * `release-notes.md` @@ -384,8 +384,6 @@ Don't translate: Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. -/// - #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. From b04d29c983bd6705bda5248f5735705f0e6d06e6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 15:21:51 +0000 Subject: [PATCH 058/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 26dc7df89..0f05df5ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo). * 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo). From 959e793297ac9f51b5811063e8f5a36059fefb35 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Thu, 15 Aug 2024 17:35:17 +0200 Subject: [PATCH 059/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/testing-dependencies.md`?= =?UTF-8?q?=20(#11995)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-dependencies.md | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-dependencies.md diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..747dd7d06 --- /dev/null +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -0,0 +1,103 @@ +# Testando Dependências com Sobreposição (Overrides) + +## Sobrepondo dependências durante os testes + +Existem alguns cenários onde você deseje sobrepor uma dependência durante os testes. + +Você não quer que a dependência original execute (e nenhuma das subdependências que você possa ter). + +Em vez disso, você deseja fornecer uma dependência diferente que será usada somente durante os testes (possivelmente apenas para alguns testes específicos) e fornecerá um valor que pode ser usado onde o valor da dependência original foi usado. + +### Casos de uso: serviço externo + +Um exemplo pode ser que você possua um provedor de autenticação externo que você precisa chamar. + +Você envia ao serviço um *token* e ele retorna um usuário autenticado. + +Este provedor pode cobrar por requisição, e chamá-lo pode levar mais tempo do que se você tivesse um usuário fixo para os testes. + +Você provavelmente quer testar o provedor externo uma vez, mas não necessariamente chamá-lo em todos os testes que executarem. + +Neste caso, você pode sobrepor (*override*) a dependência que chama o provedor, e utilizar uma dependência customizada que retorna um *mock* do usuário, apenas para os seus testes. + +### Utilize o atributo `app.dependency_overrides` + +Para estes casos, a sua aplicação **FastAPI** possui o atributo `app.dependency_overrides`. Ele é um simples `dict`. + +Para sobrepor a dependência para os testes, você coloca como chave a dependência original (a função), e como valor, a sua sobreposição da dependência (outra função). + +E então o **FastAPI** chamará a sobreposição no lugar da dependência original. + +//// tab | Python 3.10+ + +```Python hl_lines="26-27 30" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="24-25 28" +{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="28-29 32" +{!> ../../../docs_src/dependency_testing/tutorial001.py!} +``` + +//// + +/// tip | "Dica" + +Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. + +A dependência original pode estar sendo utilizada em uma *função de operação de rota*, um *docorador de operação de rota* (quando você não utiliza o valor retornado), uma chamada ao `.include_router()`, etc. + +O FastAPI ainda poderá sobrescrevê-lo. + +/// + +E então você pode redefinir as suas sobreposições (removê-las) definindo o `app.dependency_overrides` como um `dict` vazio: + +```Python +app.dependency_overrides = {} +``` + +/// tip | "Dica" + +Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). + +/// From 4fe1af494af4a0bde8a0c8efc2dbfba4ec74a89b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 15:35:41 +0000 Subject: [PATCH 060/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0f05df5ad..0f1db29f1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei). From 60fe2b19e895f0e54a577a0bca86e0dba0926d7b Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Thu, 15 Aug 2024 17:36:31 +0200 Subject: [PATCH 061/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/testing-websockets.md`=20?= =?UTF-8?q?(#11994)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-websockets.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-websockets.md diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..f458a05d4 --- /dev/null +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# Testando WebSockets + +Você pode usar o mesmo `TestClient` para testar WebSockets. + +Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: + +```Python hl_lines="27-31" +{!../../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | "Nota" + +Para mais detalhes, confira a documentação do Starlette para testar WebSockets. + +/// From e1b52cf4285c73639c30e1cefb698f783494aa8c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 15:38:02 +0000 Subject: [PATCH 062/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0f1db29f1..51dc34986 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian). From 646232121bf6138a7056bfec5ea2c54201d7e929 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Thu, 15 Aug 2024 12:38:22 -0300 Subject: [PATCH 063/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/bigger-applications.md`?= =?UTF-8?q?=20(#11971)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/bigger-applications.md | 556 +++++++++++++++++++ 1 file changed, 556 insertions(+) create mode 100644 docs/pt/docs/tutorial/bigger-applications.md diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..7137bf865 --- /dev/null +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Aplicações Maiores - Múltiplos Arquivos + +Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo. + +**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. + +/// info | "Informação" + +Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. + +/// + +## Um exemplo de estrutura de arquivos + +Digamos que você tenha uma estrutura de arquivos como esta: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | "Dica" + +Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. + +Isso permite a importação de código de um arquivo para outro. + +Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como: + +``` +from app.routers import items +``` + +/// + +* O diretório `app` contém todo o código da aplicação. Ele possui um arquivo `app/__init__.py` vazio, o que o torna um "pacote Python" (uma coleção de "módulos Python"): `app`. +* Dentro dele, o arquivo `app/main.py` está localizado em um pacote Python (diretório com `__init__.py`). Portanto, ele é um "módulo" desse pacote: `app.main`. +* Existem também um arquivo `app/dependencies.py`, assim como o `app/main.py`, ele é um "módulo": `app.dependencies`. +* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`. +* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto, é um "submódulo": `app.routers.items`. +* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`. +* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`. +* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`. + + + +A mesma estrutura de arquivos com comentários: + +``` +. +├── app # "app" é um pacote Python +│   ├── __init__.py # este arquivo torna "app" um "pacote Python" +│   ├── main.py # "main" módulo, e.g. import app.main +│   ├── dependencies.py # "dependencies" módulo, e.g. import app.dependencies +│   └── routers # "routers" é um "subpacote Python" +│   │ ├── __init__.py # torna "routers" um "subpacote Python" +│   │ ├── items.py # "items" submódulo, e.g. import app.routers.items +│   │ └── users.py # "users" submódulo, e.g. import app.routers.users +│   └── internal # "internal" é um "subpacote Python" +│   ├── __init__.py # torna "internal" um "subpacote Python" +│   └── admin.py # "admin" submódulo, e.g. import app.internal.admin +``` + +## `APIRouter` + +Vamos supor que o arquivo dedicado a lidar apenas com usuários seja o submódulo em `/app/routers/users.py`. + +Você quer manter as *operações de rota* relacionadas aos seus usuários separadas do restante do código, para mantê-lo organizado. + +Mas ele ainda faz parte da mesma aplicação/web API **FastAPI** (faz parte do mesmo "pacote Python"). + +Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter`. + +### Importar `APIRouter` + +você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Operações de Rota* com `APIRouter` + +E então você o utiliza para declarar suas *operações de rota*. + +Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". + +Todas as mesmas opções são suportadas. + +Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | "Dica" + +Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. + +/// + +Vamos incluir este `APIRouter` na aplicação principal `FastAPI`, mas primeiro, vamos verificar as dependências e outro `APIRouter`. + +## Dependências + +Vemos que precisaremos de algumas dependências usadas em vários lugares da aplicação. + +Então, as colocamos em seu próprio módulo de `dependencies` (`app/dependencies.py`). + +Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | "Dica" + +Estamos usando um cabeçalho inventado para simplificar este exemplo. + +Mas em casos reais, você obterá melhores resultados usando os [Utilitários de Segurança](security/index.md){.internal-link target=_blank} integrados. + +/// + +## Outro módulo com `APIRouter` + +Digamos que você também tenha os endpoints dedicados a manipular "itens" do seu aplicativo no módulo em `app/routers/items.py`. + +Você tem *operações de rota* para: + +* `/items/` +* `/items/{item_id}` + +É tudo a mesma estrutura de `app/routers/users.py`. + +Mas queremos ser mais inteligentes e simplificar um pouco o código. + +Sabemos que todas as *operações de rota* neste módulo têm o mesmo: + +* Path `prefix`: `/items`. +* `tags`: (apenas uma tag: `items`). +* Extra `responses`. +* `dependências`: todas elas precisam da dependência `X-Token` que criamos. + +Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como o caminho de cada *operação de rota* deve começar com `/`, como em: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...o prefixo não deve incluir um `/` final. + +Então, o prefixo neste caso é `/items`. + +Também podemos adicionar uma lista de `tags` e `responses` extras que serão aplicadas a todas as *operações de rota* incluídas neste roteador. + +E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. + +/// tip | "Dica" + +Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. + +/// + +O resultado final é que os caminhos dos itens agora são: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Elas serão marcadas com uma lista de tags que contêm uma única string `"items"`. + * Essas "tags" são especialmente úteis para os sistemas de documentação interativa automática (usando OpenAPI). +* Todas elas incluirão as `responses` predefinidas. +* Todas essas *operações de rota* terão a lista de `dependencies` avaliada/executada antes delas. + * Se você também declarar dependências em uma *operação de rota* específica, **elas também serão executadas**. + * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. + * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | "Dica" + +Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. + +/// + +/// check + +Os parâmetros `prefix`, `tags`, `responses` e `dependencies` são (como em muitos outros casos) apenas um recurso do **FastAPI** para ajudar a evitar duplicação de código. + +/// + +### Importar as dependências + +Este código reside no módulo `app.routers.items`, o arquivo `app/routers/items.py`. + +E precisamos obter a função de dependência do módulo `app.dependencies`, o arquivo `app/dependencies.py`. + +Então usamos uma importação relativa com `..` para as dependências: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Como funcionam as importações relativas + +/// tip | "Dica" + +Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. + +/// + +Um único ponto `.`, como em: + +```Python +from .dependencies import get_token_header +``` + +significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* encontre o módulo `dependencies` (um arquivo imaginário em `app/routers/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Mas esse arquivo não existe, nossas dependências estão em um arquivo em `app/dependencies.py`. + +Lembre-se de como nossa estrutura app/file se parece: + + + +--- + +Os dois pontos `..`, como em: + +```Python +from ..dependencies import get_token_header +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) reside (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso funciona corretamente! 🎉 + +--- + +Da mesma forma, se tivéssemos usado três pontos `...`, como em: + +```Python +from ...dependencies import get_token_header +``` + +isso significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* então vá para o pai daquele pacote (não há pacote pai, `app` é o nível superior 😱)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso se referiria a algum pacote acima de `app/`, com seu próprio arquivo `__init__.py`, etc. Mas não temos isso. Então, isso geraria um erro em nosso exemplo. 🚨 + +Mas agora você sabe como funciona, então você pode usar importações relativas em seus próprios aplicativos, não importa o quão complexos eles sejam. 🤓 + +### Adicione algumas `tags`, `respostas` e `dependências` personalizadas + +Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operação de rota* porque os adicionamos ao `APIRouter`. + +Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | "Dica" + +Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. + +E também terá ambas as respostas na documentação, uma para `404` e uma para `403`. + +/// + +## O principal `FastAPI` + +Agora, vamos ver o módulo em `app/main.py`. + +Aqui é onde você importa e usa a classe `FastAPI`. + +Este será o arquivo principal em seu aplicativo que une tudo. + +E como a maior parte de sua lógica agora viverá em seu próprio módulo específico, o arquivo principal será bem simples. + +### Importar `FastAPI` + +Você importa e cria uma classe `FastAPI` normalmente. + +E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Importe o `APIRouter` + +Agora importamos os outros submódulos que possuem `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". + +### Como funciona a importação + +A seção: + +```Python +from .routers import items, users +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/main.py`) reside (o diretório `app/`)... +* procure o subpacote `routers` (o diretório em `app/routers/`)... +* e dele, importe o submódulo `items` (o arquivo em `app/routers/items.py`) e `users` (o arquivo em `app/routers/users.py`)... + +O módulo `items` terá uma variável `router` (`items.router`). Esta é a mesma que criamos no arquivo `app/routers/items.py`, é um objeto `APIRouter`. + +E então fazemos o mesmo para o módulo `users`. + +Também poderíamos importá-los como: + +```Python +from app.routers import items, users +``` + +/// info | "Informação" + +A primeira versão é uma "importação relativa": + +```Python +from .routers import items, users +``` + +A segunda versão é uma "importação absoluta": + +```Python +from app.routers import items, users +``` + +Para saber mais sobre pacotes e módulos Python, leia a documentação oficial do Python sobre módulos. + +/// + +### Evite colisões de nomes + +Estamos importando o submódulo `items` diretamente, em vez de importar apenas sua variável `router`. + +Isso ocorre porque também temos outra variável chamada `router` no submódulo `users`. + +Se tivéssemos importado um após o outro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao mesmo tempo. + +Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: + +```Python hl_lines="5" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir o `APIRouter`s para `usuários` e `itens` + +Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | "Informação" + +`users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. + +E `items.router` contém o `APIRouter` dentro do arquivo `app/routers/items.py`. + +/// + +Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo principal `FastAPI`. + +Ele incluirá todas as rotas daquele roteador como parte dele. + +/// note | "Detalhe Técnico" + +Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. + +Então, nos bastidores, ele realmente funcionará como se tudo fosse o mesmo aplicativo único. + +/// + +/// check + +Você não precisa se preocupar com desempenho ao incluir roteadores. + +Isso levará microssegundos e só acontecerá na inicialização. + +Então não afetará o desempenho. ⚡ + +/// + +### Incluir um `APIRouter` com um `prefix` personalizado, `tags`, `responses` e `dependencies` + +Agora, vamos imaginar que sua organização lhe deu o arquivo `app/internal/admin.py`. + +Ele contém um `APIRouter` com algumas *operações de rota* de administração que sua organização compartilha entre vários projetos. + +Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. + +Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. + +O resultado é que em nosso aplicativo, cada uma das *operações de rota* do módulo `admin` terá: + +* O prefixo `/admin`. +* A tag `admin`. +* A dependência `get_token_header`. +* A resposta `418`. 🍵 + +Mas isso afetará apenas o `APIRouter` em nosso aplicativo, e não em nenhum outro código que o utilize. + +Assim, por exemplo, outros projetos poderiam usar o mesmo `APIRouter` com um método de autenticação diferente. + +### Incluir uma *operação de rota* + +Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastAPI`. + +Aqui fazemos isso... só para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../../docs_src/bigger_applications/app/main.py!} +``` + +e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. + +/// info | "Detalhes Técnicos" + +**Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. + +--- + +Os `APIRouter`s não são "montados", eles não são isolados do resto do aplicativo. + +Isso ocorre porque queremos incluir suas *operações de rota* no esquema OpenAPI e nas interfaces de usuário. + +Como não podemos simplesmente isolá-los e "montá-los" independentemente do resto, as *operações de rota* são "clonadas" (recriadas), não incluídas diretamente. + +/// + +## Verifique a documentação automática da API + +Agora, execute `uvicorn`, usando o módulo `app.main` e a variável `app`: + +
+ +```console +$ uvicorn app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +E abra os documentos em http://127.0.0.1:8000/docs. + +Você verá a documentação automática da API, incluindo os caminhos de todos os submódulos, usando os caminhos (e prefixos) corretos e as tags corretas: + + + +## Incluir o mesmo roteador várias vezes com `prefixos` diferentes + +Você também pode usar `.include_router()` várias vezes com o *mesmo* roteador usando prefixos diferentes. + +Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`. + +Esse é um uso avançado que você pode não precisar, mas está lá caso precise. + +## Incluir um `APIRouter` em outro + +Da mesma forma que você pode incluir um `APIRouter` em um aplicativo `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Certifique-se de fazer isso antes de incluir `router` no aplicativo `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas. From 84d69bb69aa0ca320f108dcfcfdef63f334d54d2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 15:41:45 +0000 Subject: [PATCH 064/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 51dc34986..698825493 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/bigger-applications.md`. PR [#11971](https://github.com/fastapi/fastapi/pull/11971) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n). From 5fd9ab97509ac7910caea3b704f4b4ad8086b5d3 Mon Sep 17 00:00:00 2001 From: Ben Beasley Date: Thu, 15 Aug 2024 11:51:33 -0400 Subject: [PATCH 065/356] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Allow=20Starlette?= =?UTF-8?q?=200.38.x,=20update=20the=20pin=20to=20`>=3D0.37.2,<0.39.0`=20(?= =?UTF-8?q?#11876)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c34838b83..7a8e061cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.37.2,<0.38.0", + "starlette>=0.37.2,<0.39.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From fc9107843eb26599a1f64220978f5dac2e09ab25 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 15:51:59 +0000 Subject: [PATCH 066/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 698825493..d8e7c2e20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain). + ### Docs * 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo). From 2c9801720020b3f21295414b65d25836370100fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 15 Aug 2024 13:38:43 -0500 Subject: [PATCH 067/356] =?UTF-8?q?=F0=9F=91=B7=20Do=20not=20sync=20labels?= =?UTF-8?q?=20as=20it=20overrides=20manually=20added=20labels=20(#12024)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/labeler.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index d62f1668d..c3bb83f9a 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -17,8 +17,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/labeler@v5 - with: - sync-labels: true # Run this after labeler applied labels check-labels: needs: From 2f5ed4f2d1433f09b82868c2002158bf87897cc0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 18:39:22 +0000 Subject: [PATCH 068/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d8e7c2e20..1311be390 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). * 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo). From 0d92b42ff08a90bc180784acb6dd8d1f7681c951 Mon Sep 17 00:00:00 2001 From: Pierre V-F <74793957+Pierre-VF@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:50:31 +0200 Subject: [PATCH 069/356] =?UTF-8?q?=F0=9F=94=A7=20Add=20changelog=20URL=20?= =?UTF-8?q?to=20`pyproject.toml`,=20shows=20in=20PyPI=20(#11152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 7a8e061cc..dc04fcdfe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,8 @@ dependencies = [ Homepage = "https://github.com/fastapi/fastapi" Documentation = "https://fastapi.tiangolo.com/" Repository = "https://github.com/fastapi/fastapi" +Issues = "https://github.com/fastapi/fastapi/issues" +Changelog = "https://fastapi.tiangolo.com/release-notes/" [project.optional-dependencies] From b7c80cbca2f27758ee90281b3417f76bdce60242 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 18:51:01 +0000 Subject: [PATCH 070/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1311be390..dc81963cf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF). * 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo). From 285a54cfbd4a469e4cac72ed053f850d4cdbbd4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 15:56:19 -0500 Subject: [PATCH 071/356] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.8.14=20to=201.9.0=20(#11727)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.14 to 1.9.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.14...v1.9.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e7c69befc..591df634b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.14 + uses: pypa/gh-action-pypi-publish@v1.9.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 94be8ff3417f47d11389e9ab1d759f026db6a07e Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 20:58:06 +0000 Subject: [PATCH 072/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index dc81963cf..b58e60203 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.14 to 1.9.0. PR [#11727](https://github.com/fastapi/fastapi/pull/11727) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF). * 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo). * 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo). From 4f937c0c4afbd0b46cf2db91acac6814504bbdcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 15 Aug 2024 16:00:47 -0500 Subject: [PATCH 073/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b58e60203..7245d072a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.1 + ### Upgrades * ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 3413dffc8..0b79d45ef 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.0" +__version__ = "0.112.1" from starlette import status as status From 86c8f4fc2b1d9157be7bf78535a336d69049fbc5 Mon Sep 17 00:00:00 2001 From: Cedric L'homme Date: Thu, 15 Aug 2024 23:29:58 +0200 Subject: [PATCH 074/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs/en/docs/t?= =?UTF-8?q?utorial/body.md`=20with=20Python=203.10=20union=20type=20exampl?= =?UTF-8?q?e=20(#11415)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/body.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index f3a8685c6..44d2d7da6 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -237,7 +237,9 @@ The function parameters will be recognized as follows: FastAPI will know that the value of `q` is not required because of the default value `= None`. -The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors. +The `str | None` (Python 3.10+) or `Union` in `Union[str, None]` (Python 3.8+) is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`. + +But adding the type annotations will allow your editor to give you better support and detect errors. /// From 366bdebd9eea7018660957271da40dfd5959537d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 21:30:26 +0000 Subject: [PATCH 075/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7245d072a..be8682f48 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). + ## 0.112.1 ### Upgrades From 2cb1333b971ae17b83499bca952a7803cec21b0c Mon Sep 17 00:00:00 2001 From: Luke Okomilo Date: Thu, 15 Aug 2024 23:31:16 +0100 Subject: [PATCH 076/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20inconsistent=20res?= =?UTF-8?q?ponse=20code=20when=20item=20already=20exists=20in=20docs=20for?= =?UTF-8?q?=20testing=20(#11818)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs_src/app_testing/app_b_an/main.py | 2 +- docs_src/app_testing/app_b_an/test_main.py | 2 +- docs_src/app_testing/app_b_an_py310/main.py | 2 +- docs_src/app_testing/app_b_an_py310/test_main.py | 2 +- docs_src/app_testing/app_b_an_py39/main.py | 2 +- docs_src/app_testing/app_b_an_py39/test_main.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py index c63134fc9..c66278fdd 100644 --- a/docs_src/app_testing/app_b_an/main.py +++ b/docs_src/app_testing/app_b_an/main.py @@ -34,6 +34,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py310/main.py b/docs_src/app_testing/app_b_an_py310/main.py index 48c27a0b8..c5952be0b 100644 --- a/docs_src/app_testing/app_b_an_py310/main.py +++ b/docs_src/app_testing/app_b_an_py310/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py39/main.py b/docs_src/app_testing/app_b_an_py39/main.py index 935a510b7..142e23a26 100644 --- a/docs_src/app_testing/app_b_an_py39/main.py +++ b/docs_src/app_testing/app_b_an_py39/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} From 4636c621a957ddfb927e3a1dd49fee521ee7f5d5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 22:31:36 +0000 Subject: [PATCH 077/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index be8682f48..decd54c99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). ## 0.112.1 From 265dbeb6635864e527cfd4c7376f0b32bc2301c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jun-Ah=20=EC=A4=80=EC=95=84?= Date: Fri, 16 Aug 2024 07:38:02 +0900 Subject: [PATCH 078/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20missing=20`compres?= =?UTF-8?q?slevel`=20parameter=20on=20docs=20for=20`GZipMiddleware`=20(#11?= =?UTF-8?q?350)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/middleware.md | 1 + docs_src/advanced_middleware/tutorial003.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 4b273fd89..57e476167 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -88,6 +88,7 @@ The middleware will handle both standard and streaming responses. The following arguments are supported: * `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`. +* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes. ## Other middlewares diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py index b99e3edd1..e2c87e67d 100644 --- a/docs_src/advanced_middleware/tutorial003.py +++ b/docs_src/advanced_middleware/tutorial003.py @@ -3,7 +3,7 @@ from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() -app.add_middleware(GZipMiddleware, minimum_size=1000) +app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5) @app.get("/") From 3c8d0abc87579fdcd7bf1a9045b62d363fed0077 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 22:38:22 +0000 Subject: [PATCH 079/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index decd54c99..3bee16617 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). From 8809b3685f2778b9b4b1f3edb44523cee36fdccf Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Fri, 16 Aug 2024 01:30:12 +0200 Subject: [PATCH 080/356] =?UTF-8?q?=F0=9F=93=9D=20Several=20docs=20improve?= =?UTF-8?q?ments,=20tweaks,=20and=20clarifications=20(#11390)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- docs/de/docs/features.md | 2 +- docs/en/docs/advanced/additional-responses.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 2 +- docs/en/docs/advanced/custom-response.md | 4 ++-- docs/en/docs/advanced/openapi-callbacks.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- docs/en/docs/advanced/settings.md | 4 ++-- docs/en/docs/features.md | 2 +- docs/en/docs/help-fastapi.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/background-tasks.md | 2 +- docs/en/docs/tutorial/body-nested-models.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/cookie-params.md | 2 +- docs/en/docs/tutorial/cors.md | 6 +++--- .../dependencies/dependencies-with-yield.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/extra-models.md | 6 +++--- docs/en/docs/tutorial/header-params.md | 2 +- .../docs/tutorial/query-params-str-validations.md | 14 +++++++------- docs/en/docs/tutorial/request-files.md | 2 +- docs/en/docs/tutorial/response-model.md | 10 +++++----- docs/en/docs/tutorial/schema-extra-example.md | 2 +- 24 files changed, 40 insertions(+), 40 deletions(-) diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index b268604fa..8fdf42622 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -6,7 +6,7 @@ ### Basiert auf offenen Standards -* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Body-Anfragen, Sicherheit, usw. +* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Requestbodys, Sicherheit, usw. * Automatische Dokumentation der Datenmodelle mit JSON Schema (da OpenAPI selbst auf JSON Schema basiert). * Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. * Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 95ca90f6b..07d99df5f 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -40,7 +40,7 @@ Keep in mind that you have to return the `JSONResponse` directly. The `model` key is not part of OpenAPI. -**FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place. The correct place is: diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 0447a7220..5ff64016c 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -211,7 +211,7 @@ Now create that other file `routes.toml`: This file configures Traefik to use the path prefix `/api/v1`. -And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. +And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. Now start Traefik: diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index f31127efe..8a6555dba 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -255,11 +255,11 @@ This includes many libraries to interact with cloud storage, video processing, a 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. -3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function. +3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function (`iterfile`). So, it is a generator function that transfers the "generating" work to something else internally. - By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. + By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing. /// tip diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index e74af3d3e..7fead2ed9 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -37,7 +37,7 @@ This part is pretty normal, most of the code is probably already familiar to you /// tip -The `callback_url` query parameter uses a Pydantic URL type. +The `callback_url` query parameter uses a Pydantic Url type. /// diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 33e10d091..73071ed1b 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -54,7 +54,7 @@ Now, let's see how you could use that to return a custom response. Let's say that you want to return an XML response. -You could put your XML content in a string, put it in a `Response`, and return it: +You could put your XML content in a string, put that in a `Response`, and return it: ```Python hl_lines="1 18" {!../../../docs_src/response_directly/tutorial002.py!} diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 69b8fa7d2..48798ebac 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -725,7 +725,7 @@ Here's how the hierarchy of dependencies and scopes looks like: * This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so: * `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`. * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. - * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. + * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either. /// tip diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index b77557361..b78f83953 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -138,7 +138,7 @@ That means that any value read in Python from an environment variable will be a ## Pydantic `Settings` -Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. ### Install `pydantic-settings` @@ -411,7 +411,7 @@ And then update your `config.py` with: /// tip -The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. +The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic: Concepts: Configuration. /// diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 1a871a22b..9c38a4bd2 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -6,7 +6,7 @@ ### Based on open standards -* OpenAPI for API creation, including declarations of path operations, parameters, body requests, security, etc. +* OpenAPI for API creation, including declarations of path operations, parameters, request bodies, security, etc. * Automatic data model documentation with JSON Schema (as OpenAPI itself is based on JSON Schema). * Designed around these standards, after a meticulous study. Instead of an afterthought layer on top. * This also allows using automatic **client code generation** in many languages. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index cd367dd6b..81151032f 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -66,7 +66,7 @@ I love to hear about how **FastAPI** is being used, what you have liked in it, i ## Vote for FastAPI * Vote for **FastAPI** in Slant. -* Vote for **FastAPI** in AlternativeTo. +* Vote for **FastAPI** in AlternativeTo. * Say you use **FastAPI** on StackShare. ## Help others with questions in GitHub diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 900ede22c..4ed1fc680 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -519,7 +519,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t /// tip -Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. +Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. /// diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 5370b9ba8..8b4476e41 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -9,7 +9,7 @@ This includes, for example: * Email notifications sent after performing an action: * As connecting to an email server and sending an email tends to be "slow" (several seconds), you can return the response right away and send the email notification in the background. * Processing data: - * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process it in the background. + * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process the file in the background. ## Using `BackgroundTasks` diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index f823a9033..d2bda5979 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -220,7 +220,7 @@ Again, doing just that declaration, with **FastAPI** you get: Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`. -To see all the options you have, checkout the docs for Pydantic's exotic types. You will see some examples in the next chapter. +To see all the options you have, checkout Pydantic's Type Overview. You will see some examples in the next chapter. For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`: diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 44d2d7da6..608b50dbb 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -4,7 +4,7 @@ When you need to send data from a client (let's say, a browser) to your API, you A **request** body is data sent by the client to your API. A **response** body is the data your API sends to the client. -Your API almost always has to send a **response** body. But clients don't necessarily need to send **request** bodies all the time. +Your API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body. To declare a **request** body, you use Pydantic models with all their power and benefits. diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 6196b34d0..0214a9c38 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible. Then declare the cookie parameters using the same structure as with `Path` and `Query`. -The first value is the default value, you can pass all the extra validation or annotation parameters: +You can define the default value as well as all the extra validation or annotation parameters: //// tab | Python 3.10+ diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 665249ffa..fd329e138 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -18,11 +18,11 @@ Even if they are all in `localhost`, they use different protocols or ports, so, So, let's say you have a frontend running in your browser at `http://localhost:8080`, and its JavaScript is trying to communicate with a backend running at `http://localhost` (because we don't specify a port, the browser will assume the default port `80`). -Then, the browser will send an HTTP `OPTIONS` request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the browser will let the JavaScript in the frontend send its request to the backend. +Then, the browser will send an HTTP `OPTIONS` request to the `:80`-backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the `:8080`-browser will let the JavaScript in the frontend send its request to the `:80`-backend. -To achieve this, the backend must have a list of "allowed origins". +To achieve this, the `:80`-backend must have a list of "allowed origins". -In this case, it would have to include `http://localhost:8080` for the frontend to work correctly. +In this case, the list would have to include `http://localhost:8080` for the `:8080`-frontend to work correctly. ## Wildcards diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 279fc4d1e..2a3ac2237 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -6,7 +6,7 @@ To do this, use `yield` instead of `return`, and write the extra steps (code) af /// tip -Make sure to use `yield` one single time. +Make sure to use `yield` one single time per dependency. /// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index aed9f7880..849dee41f 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Here are some of the additional data types you can use: * `datetime.timedelta`: * A Python `datetime.timedelta`. * In requests and responses will be represented as a `float` of total seconds. - * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info. + * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info. * `frozenset`: * In requests and responses, treated the same as a `set`: * In requests, a list will be read, eliminating duplicates and converting it to a `set`. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 982f59782..1c87e76ce 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -156,7 +156,7 @@ UserInDB( /// warning -The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security. +The supporting additional functions `fake_password_hasher` and `fake_save_user` are just to demo a possible flow of the data, but they of course are not providing any real security. /// @@ -194,7 +194,7 @@ That way, we can declare just the differences between the models (with plaintext ## `Union` or `anyOf` -You can declare a response to be the `Union` of two types, that means, that the response would be any of the two. +You can declare a response to be the `Union` of two or more types, that means, that the response would be any of them. It will be defined in OpenAPI with `anyOf`. @@ -234,7 +234,7 @@ If it was in a type annotation we could have used the vertical bar, as: some_variable: PlaneItem | CarItem ``` -But if we put that in `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation. +But if we put that in the assignment `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation. ## List of models diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index cc5975b85..2e07fe0e6 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -62,7 +62,7 @@ Prefer to use the `Annotated` version if possible. Then declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`. -The first value is the default value, you can pass all the extra validation or annotation parameters: +You can define the default value as well as all the extra validation or annotation parameters: //// tab | Python 3.10+ diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index ce7d0580d..859242d93 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -155,7 +155,7 @@ FastAPI will now: * Show a **clear error** for the client when the data is not valid * **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**) -## Alternative (old) `Query` as the default value +## Alternative (old): `Query` as the default value Previous versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you. @@ -209,7 +209,7 @@ q: str | None = Query(default=None) q: str | None = None ``` -But it declares it explicitly as being a query parameter. +But the `Query` versions declare it explicitly as being a query parameter. /// info @@ -457,7 +457,7 @@ Having a default value of any type, including `None`, makes the parameter option /// -## Make it required +## Required parameters When we don't need to declare more validations or metadata, we can make the `q` query parameter required just by not declaring a default value, like: @@ -573,7 +573,7 @@ It is used by Pydantic and FastAPI to explicitly declare that a value is require This will let **FastAPI** know that this parameter is required. -### Required with `None` +### Required, can be `None` You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. @@ -633,7 +633,7 @@ Prefer to use the `Annotated` version if possible. /// tip -Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. +Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required fields. /// @@ -809,7 +809,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: } ``` -#### Using `list` +#### Using just `list` You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): @@ -1107,7 +1107,7 @@ The docs will show it like this: -## Exclude from OpenAPI +## Exclude parameters from OpenAPI To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index ceaea3626..53d9eefde 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -152,7 +152,7 @@ Using `UploadFile` has several advantages over `bytes`: * `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`). * `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`). -* `file`: A `SpooledTemporaryFile` (a file-like object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object. +* `file`: A `SpooledTemporaryFile` (a file-like object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a "file-like" object. `UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`). diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 8a2dccc81..991deca12 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -236,9 +236,9 @@ That's why in this example we have to declare it in the `response_model` paramet ## Return Type and Data Filtering -Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**. +Let's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**. -We want FastAPI to keep **filtering** the data using the response model. +We want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model. In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type. @@ -306,7 +306,7 @@ The most common case would be [returning a Response directly as explained later {!> ../../../docs_src/response_model/tutorial003_02.py!} ``` -This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`. +This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct. @@ -455,7 +455,7 @@ The examples here use `.dict()` for compatibility with Pydantic v1, but you shou /// info -FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. +FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. /// @@ -466,7 +466,7 @@ You can also use: * `response_model_exclude_defaults=True` * `response_model_exclude_none=True` -as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. +as described in the Pydantic docs for `exclude_defaults` and `exclude_none`. /// diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 141a0bc55..70745b048 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -44,7 +44,7 @@ That extra info will be added as-is to the output **JSON Schema** for that model //// tab | Pydantic v2 -In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config. +In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Configuration. You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`. From 470f1ae57dfef889ce8ec8ad29887f3022df6cf1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 15 Aug 2024 23:30:36 +0000 Subject: [PATCH 081/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3bee16617..1d610e078 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). From a0c529ef0a87517eb6accec1000ccfd52761905d Mon Sep 17 00:00:00 2001 From: Micael Jarniac Date: Thu, 15 Aug 2024 21:04:55 -0300 Subject: [PATCH 082/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typo=20(#1?= =?UTF-8?q?2026)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 48798ebac..ff52d7bb8 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -398,7 +398,7 @@ Now update the dependency `get_current_user`. This is the one used by the dependencies above. -Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. +Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes. From e8f7bf0ad5e6a3fefa13face9ee9864b255b8ee5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 00:05:21 +0000 Subject: [PATCH 083/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1d610e078..2442259fd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201). * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). From 0aaaed581e59a95ab4ce6d18c26d6881c0782990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C5=82awomir=20Ehlert?= Date: Fri, 16 Aug 2024 03:57:38 +0200 Subject: [PATCH 084/356] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20Record=20and=20sho?= =?UTF-8?q?w=20test=20coverage=20contexts=20(what=20test=20covers=20which?= =?UTF-8?q?=20line)=20(#11518)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- pyproject.toml | 1 + scripts/test-cov-html.sh | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index dc04fcdfe..982ae3ed1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -184,6 +184,7 @@ source = [ "fastapi" ] context = '${CONTEXT}' +dynamic_context = "test_function" omit = [ "docs_src/response_model/tutorial003_04.py", "docs_src/response_model/tutorial003_04_py310.py", diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index d1bdfced2..85aef9601 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -6,4 +6,4 @@ set -x bash scripts/test.sh ${@} coverage combine coverage report --show-missing -coverage html +coverage html --show-contexts From a51a98b07e69e801dda445d76ac48093661044d7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 01:58:02 +0000 Subject: [PATCH 085/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2442259fd..e6ef19ed3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,10 @@ hide: * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). +### Internal + +* ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). + ## 0.112.1 ### Upgrades From 10eee5c3b37440d8c1b3684df4676722f8c8d0fe Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 15 Aug 2024 21:04:50 -0500 Subject: [PATCH 086/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/project-generation.md`=20(#11947)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/project-generation.md | 1 + docs/es/docs/project-generation.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 docs/es/docs/project-generation.md diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index d142862ee..61459ba53 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -16,6 +16,7 @@ GitHub Repository: email_validator - for email validation. +* email-validator - for email validation. Used by Starlette: diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 90864a98e..b5d7f8f92 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -442,7 +442,7 @@ Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən Pydantic tərəfindən istifadə olunanlar: -* email_validator - e-poçtun yoxlanılması üçün. +* email-validator - e-poçtun yoxlanılması üçün. * pydantic-settings - parametrlərin idarə edilməsi üçün. * pydantic-extra-types - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün. diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 042cf9399..c882506ff 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -439,7 +439,7 @@ item: Item Pydantic দ্বারা ব্যবহৃত: -- email_validator - ইমেল যাচাইকরণের জন্য। +- email-validator - ইমেল যাচাইকরণের জন্য। স্টারলেট দ্বারা ব্যবহৃত: diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 3789c5998..af024d18d 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -449,7 +449,7 @@ Um mehr darüber zu erfahren, siehe den Abschnitt email_validator - für E-Mail-Validierung. +* email-validator - für E-Mail-Validierung. * pydantic-settings - für die Verwaltung von Einstellungen. * pydantic-extra-types - für zusätzliche Typen, mit Pydantic zu verwenden. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index 3f632b1cb..b480780bc 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw /// info -Um `EmailStr` zu verwenden, installieren Sie zuerst `email_validator`. +Um `EmailStr` zu verwenden, installieren Sie zuerst `email-validator`. Z. B. `pip install email-validator` oder `pip install pydantic[email]`. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index dc8c4f023..aa7542366 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -451,7 +451,7 @@ item: Item ⚙️ Pydantic: -* email_validator - 📧 🔬. +* email-validator - 📧 🔬. ⚙️ 💃: diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index caae47d14..9483508aa 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** /// info -⚙️ `EmailStr`, 🥇 ❎ `email_validator`. +⚙️ `EmailStr`, 🥇 ❎ `email-validator`. 🤶 Ⓜ. `pip install email-validator` ⚖️ `pip install pydantic[email]`. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 4fe0cd6cc..d76ef498b 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -458,7 +458,7 @@ When you install FastAPI with `pip install "fastapi[standard]"` it comes the `st Used by Pydantic: -* email_validator - for email validation. +* email-validator - for email validation. Used by Starlette: diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 991deca12..c17e32f90 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: /// info -To use `EmailStr`, first install `email_validator`. +To use `EmailStr`, first install `email-validator`. E.g. `pip install email-validator` or `pip install pydantic[email]`. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 2b6a2f0be..fe4912253 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -437,7 +437,7 @@ Para entender más al respecto revisa la sección email_validator - para validación de emails. +* email-validator - para validación de emails. Usados por Starlette: diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index bc8b77941..1ae566a9f 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -442,7 +442,7 @@ item: Item استفاده شده توسط Pydantic: -* email_validator - برای اعتبارسنجی آدرس‌های ایمیل. +* email-validator - برای اعتبارسنجی آدرس‌های ایمیل. استفاده شده توسط Starlette: diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 927c0c643..dccefdd5a 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -449,7 +449,7 @@ Pour en savoir plus, consultez la section email_validator - pour la validation des adresses email. +* email-validator - pour la validation des adresses email. Utilisées par Starlette : diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 3af166ab0..23a2eb824 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -446,7 +446,7 @@ item: Item בשימוש Pydantic: -- email_validator - לאימות כתובות אימייל. +- email-validator - לאימות כתובות אימייל. בשימוש Starlette: diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index e605bbb55..8e326a78b 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -443,7 +443,7 @@ Ezeknek a további megértéséhez: email_validator - e-mail validációkra. +* email-validator - e-mail validációkra. * pydantic-settings - Beállítások követésére. * pydantic-extra-types - Extra típusok Pydantic-hoz. diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 272f9a37e..57940f0ed 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -437,7 +437,7 @@ Per approfondire, consulta la sezione email_validator - per la validazione di email. +* email-validator - per la validazione di email. Usate da Starlette: diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index c066c5070..72a0e98bc 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -435,7 +435,7 @@ item: Item Pydantic によって使用されるもの: -- email_validator - E メールの検証 +- email-validator - E メールの検証 Starlette によって使用されるもの: diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 620fcc881..8b00d90bc 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -441,7 +441,7 @@ item: Item Pydantic이 사용하는: -* email_validator - 이메일 유효성 검사. +* email-validator - 이메일 유효성 검사. Starlette이 사용하는: diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index efa9abfc3..e591e1c9d 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -439,7 +439,7 @@ Aby dowiedzieć się o tym więcej, zobacz sekcję email_validator - dla walidacji adresów email. +* email-validator - dla walidacji adresów email. Używane przez Starlette: diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index bdaafdefc..f99144617 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -434,7 +434,7 @@ Para entender mais sobre performance, veja a seção email_validator - para validação de email. +* email-validator - para validação de email. Usados por Starlette: diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 313e980d8..3aa4d82d0 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -443,7 +443,7 @@ item: Item Используется Pydantic: -* email_validator - для проверки электронной почты. +* email-validator - для проверки электронной почты. Используется Starlette: diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 38d185b98..f8c910fe9 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -131,7 +131,7 @@ FastAPI будет использовать значение `response_model` д /// info | "Информация" -Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. +Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`. Используйте `pip install email-validator` или `pip install pydantic[email]`. diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 7d96b4edc..7ecaf1ba3 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -449,7 +449,7 @@ Daha fazla bilgi için, bu bölüme bir göz at email_validator - email doğrulaması için. +* email-validator - email doğrulaması için. * pydantic-settings - ayar yönetimi için. * pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index ffcb8fd13..4c8c54af2 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -437,7 +437,7 @@ item: Item Pydantic використовує: -* email_validator - для валідації електронної пошти. +* email-validator - для валідації електронної пошти. * pydantic-settings - для управління налаштуваннями. * pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 5fc1400fd..09deac6f2 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -452,7 +452,7 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch Sử dụng bởi Pydantic: -* email_validator - cho email validation. +* email-validator - cho email validation. Sử dụng Starlette: diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index eb20adbb5..ee7f56220 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -449,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn email_validator - fún ifọwọsi ímeèlì. +* email-validator - fún ifọwọsi ímeèlì. * pydantic-settings - fún ètò ìsàkóso. * pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic. diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index c98a3098f..d260b5b79 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -443,7 +443,7 @@ item: Item 用於 Pydantic: -- email_validator - 用於電子郵件驗證。 +- email-validator - 用於電子郵件驗證。 - pydantic-settings - 用於設定管理。 - pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d1238fdd2..777240ec2 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -446,7 +446,7 @@ item: Item 用于 Pydantic: -* email_validator - 用于 email 校验。 +* email-validator - 用于 email 校验。 用于 Starlette: diff --git a/pyproject.toml b/pyproject.toml index 982ae3ed1..9e0611387 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,7 +64,7 @@ standard = [ # For forms and file uploads "python-multipart >=0.0.7", # To validate email fields - "email_validator >=2.0.0", + "email-validator >=2.0.0", # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", # TODO: this should be part of some pydantic optional extra dependencies @@ -91,7 +91,7 @@ all = [ # For ORJSONResponse "orjson >=3.2.1", # To validate email fields - "email_validator >=2.0.0", + "email-validator >=2.0.0", # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", # Settings management From 9f78e08c146b27c1c92f812e99c14b057ff9ea08 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 16:50:25 +0000 Subject: [PATCH 089/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 584ca4354..ab0024220 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). * 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann). From fd5c00ab7609290638a80925c055a77eafad6879 Mon Sep 17 00:00:00 2001 From: VaitoSoi Date: Fri, 16 Aug 2024 23:51:25 +0700 Subject: [PATCH 090/356] =?UTF-8?q?=F0=9F=93=9D=20Edit=20the=20link=20to?= =?UTF-8?q?=20the=20OpenAPI=20"Responses=20Object"=20and=20"Response=20Obj?= =?UTF-8?q?ect"=20sections=20in=20the=20"Additional=20Responses=20in=20Ope?= =?UTF-8?q?nAPI"=20section=20(#11996)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg --- docs/en/docs/advanced/additional-responses.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 07d99df5f..674f0672c 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -251,5 +251,5 @@ For example: To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification: -* OpenAPI Responses Object, it includes the `Response Object`. -* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. +* OpenAPI Responses Object, it includes the `Response Object`. +* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. From 46d0ffc0d712f7e09509d5742f0454ddfa03e8ad Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 16:52:46 +0000 Subject: [PATCH 091/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ab0024220..40103a3b0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). * 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac). From f79247b4e581819c55afb761b5f6a702db03cc11 Mon Sep 17 00:00:00 2001 From: gitworkflows <118260833+gitworkflows@users.noreply.github.com> Date: Fri, 16 Aug 2024 22:56:19 +0600 Subject: [PATCH 092/356] =?UTF-8?q?=F0=9F=99=88=20Add=20.coverage*=20to=20?= =?UTF-8?q?`.gitignore`=20(#11940)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9be494cec..ef6364a9a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ __pycache__ htmlcov dist site -.coverage +.coverage* coverage.xml .netlify test.db From 9a939dec47311fdd8d05c6ea57ed8d53578af1be Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 16:56:43 +0000 Subject: [PATCH 093/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 40103a3b0..951033e4a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). ## 0.112.1 From ff8fcd3b44626ab830f09a2c559530f1440cc844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 16 Aug 2024 12:29:21 -0500 Subject: [PATCH 094/356] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20griffe-t?= =?UTF-8?q?ypingdoc=20for=20the=20docs=20(#12029)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index a7ef7ef2e..ab2b0165b 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -12,7 +12,7 @@ pillow==10.3.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 -griffe-typingdoc==0.2.5 +griffe-typingdoc==0.2.6 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 From 2e0f74f58b9cb67f84b2bcf47dc082c74ba7483f Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 17:29:43 +0000 Subject: [PATCH 095/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 951033e4a..cc3fee1c1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). From 46412ff67d5a0d04b95e6206f9ed050c13db47f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 16 Aug 2024 12:44:28 -0500 Subject: [PATCH 096/356] =?UTF-8?q?=F0=9F=94=8A=20Remove=20old=20ignore=20?= =?UTF-8?q?warnings=20(#11950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9e0611387..8db2d2b2d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -149,27 +149,14 @@ xfail_strict = true junit_family = "xunit2" filterwarnings = [ "error", - # TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8 - 'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio', 'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette', - # TODO: remove after upgrading HTTPX to a version newer than 0.23.0 - # Including PR: https://github.com/encode/httpx/pull/2309 - "ignore:'cgi' is deprecated:DeprecationWarning", # For passlib "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - # TODO remove pytest-cov - 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', - # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 - # also, if it won't receive an update, consider replacing python-jose with some alternative - # related issues: - # - https://github.com/mpdavis/python-jose/issues/332 - # - https://github.com/mpdavis/python-jose/issues/334 - 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', # Trio 24.1.0 raises a warning from attrs # Ref: https://github.com/python-trio/trio/pull/3054 # Remove once there's a new version of Trio From 29babdc0a1974bb331330c20c24d588a26264a5f Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 17:44:48 +0000 Subject: [PATCH 097/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cc3fee1c1..a5c713e03 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). * ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs). From be7e7d44334adf4358125224488488910c39f5a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 16 Aug 2024 17:45:47 +0000 Subject: [PATCH 098/356] =?UTF-8?q?=E2=AC=86=20Update=20sqlalchemy=20requi?= =?UTF-8?q?rement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- updated-dependencies: - dependency-name: sqlalchemy dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index bfe70f2f5..801cf9dd4 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -7,7 +7,7 @@ ruff ==0.2.0 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel -sqlalchemy >=1.3.18,<1.4.43 +sqlalchemy >=1.3.18,<2.0.33 databases[sqlite] >=0.3.2,<0.7.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 From daf4970ed7c8da680c2dd550d6346861c8eb0ace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 16 Aug 2024 16:56:33 -0500 Subject: [PATCH 099/356] =?UTF-8?q?=F0=9F=93=9D=20Clarify=20management=20t?= =?UTF-8?q?asks=20for=20translations,=20multiples=20files=20in=20one=20PR?= =?UTF-8?q?=20(#12030)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/management-tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/management-tasks.md b/docs/en/docs/management-tasks.md index 815bad539..7e7aa3baf 100644 --- a/docs/en/docs/management-tasks.md +++ b/docs/en/docs/management-tasks.md @@ -113,7 +113,7 @@ For the other languages, confirm that: * The title is correct following the instructions above. * It has the labels `lang-all` and `lang-{lang code}`. * The PR changes only one Markdown file adding a translation. - * Or in some cases, at most two files, if they are small and people reviewed them. + * Or in some cases, at most two files, if they are small, for the same language, and people reviewed them. * If it's the first translation for that language, it will have additional `mkdocs.yml` files, for those cases follow the instructions below. * The PR doesn't add any additional or extraneous files. * The translation seems to have a similar structure as the original English file. From 7ed9a4971e0b4b2e5ec3ac3dd22f3146b911fc7a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 21:56:54 +0000 Subject: [PATCH 100/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a5c713e03..7197e803c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). * 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev). From beedc72281a12379e6c2e621d3db13726b787851 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 22:32:33 +0000 Subject: [PATCH 101/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7197e803c..da1094ea6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). * 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows). From 8a146b7a28a46f141f3f3be0b74cd6d11fb823ff Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Fri, 16 Aug 2024 18:18:02 -0500 Subject: [PATCH 102/356] =?UTF-8?q?=F0=9F=94=A5=20Remove=20Sentry=20link?= =?UTF-8?q?=20from=20Advanced=20Middleware=20docs=20(#12031)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/middleware.md | 1 - docs/em/docs/advanced/middleware.md | 1 - docs/en/docs/advanced/middleware.md | 1 - docs/zh/docs/advanced/middleware.md | 1 - 4 files changed, 4 deletions(-) diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 4116b30ec..8912225fb 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -95,7 +95,6 @@ Es gibt viele andere ASGI-Middlewares. Zum Beispiel: -* Sentry * Uvicorns `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 89f494aa3..e3cc389c6 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -95,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🖼: -* 🔫 * Uvicorn `ProxyHeadersMiddleware` * 🇸🇲 diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 57e476167..70415adca 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -96,7 +96,6 @@ There are many other ASGI middlewares. For example: -* Sentry * Uvicorn's `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 764784ce3..926082b94 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -95,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 例如: -* Sentry * Uvicorn 的 `ProxyHeadersMiddleware` * MessagePack From 8b05d4518b64ec18938e76954d4ecf6bd9f289b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 16 Aug 2024 23:18:21 +0000 Subject: [PATCH 103/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index da1094ea6..9d8513faf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). * 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar). From 957d747d21d07db306a45015178d902367c89342 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Sat, 17 Aug 2024 05:57:21 +0200 Subject: [PATCH 104/356] =?UTF-8?q?=F0=9F=93=9D=20Highlight=20correct=20li?= =?UTF-8?q?ne=20in=20tutorial=20`docs/en/docs/tutorial/body-multiple-param?= =?UTF-8?q?s.md`=20(#11978)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Esteban Maya --- docs/en/docs/tutorial/body-multiple-params.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 3adfcd4d1..511fb358e 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -228,7 +228,7 @@ For example: //// tab | Python 3.10+ -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` @@ -236,7 +236,7 @@ For example: //// tab | Python 3.9+ -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` @@ -244,7 +244,7 @@ For example: //// tab | Python 3.8+ -```Python hl_lines="28" +```Python hl_lines="29" {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} ``` @@ -258,7 +258,7 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="25" +```Python hl_lines="26" {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` @@ -272,7 +272,7 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="27" +```Python hl_lines="28" {!> ../../../docs_src/body_multiple_params/tutorial004.py!} ``` From 263e46e5403a78d9bdf249338ed382affe01eb1a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 03:57:45 +0000 Subject: [PATCH 105/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9d8513faf..314ea19c5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). * 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi). From 4a7f6e0ae66fb1d2b08aee5035df895074dccdfa Mon Sep 17 00:00:00 2001 From: gitworkflows <118260833+gitworkflows@users.noreply.github.com> Date: Sat, 17 Aug 2024 09:59:06 +0600 Subject: [PATCH 106/356] =?UTF-8?q?=F0=9F=94=A8=20Standardize=20shebang=20?= =?UTF-8?q?across=20shell=20scripts=20(#11942)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/format.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/format.sh b/scripts/format.sh index 45742f79a..bf70f42e5 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,4 +1,4 @@ -#!/bin/sh -e +#!/usr/bin/env bash set -x ruff check fastapi tests docs_src scripts --fix From 6433c3b70e696398b6cedd33025007960744c281 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 04:00:12 +0000 Subject: [PATCH 107/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 314ea19c5..bd70a80ff 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo). From 3a3ad5d66d0cae4be95675b93d8ee8b10c3ce212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 16 Aug 2024 23:13:50 -0500 Subject: [PATCH 108/356] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20version?= =?UTF-8?q?=20of=20Ruff=20and=20reformat=20(#12032)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .github/actions/people/app/main.py | 6 +++--- .pre-commit-config.yaml | 2 +- fastapi/dependencies/utils.py | 6 +++--- fastapi/routing.py | 12 ++++++------ fastapi/utils.py | 6 +++--- requirements-tests.txt | 2 +- tests/test_dependency_contextmanager.py | 6 +++--- tests/test_inherited_custom_class.py | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 33156f1ca..b752d9d2b 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -515,9 +515,9 @@ def get_individual_sponsors(settings: Settings): tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict) for node in nodes: - tiers[node.tier.monthlyPriceInDollars][ - node.sponsorEntity.login - ] = node.sponsorEntity + tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( + node.sponsorEntity + ) return tiers diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4d49845d6..1ed005657 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.2.0 + rev: v0.6.1 hooks: - id: ruff args: diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 4f984177a..3e8e7b410 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -342,9 +342,9 @@ def analyze_param( if isinstance(arg, (params.Param, params.Body, params.Depends)) ] if fastapi_specific_annotations: - fastapi_annotation: Union[ - FieldInfo, params.Depends, None - ] = fastapi_specific_annotations[-1] + fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( + fastapi_specific_annotations[-1] + ) else: fastapi_annotation = None if isinstance(fastapi_annotation, FieldInfo): diff --git a/fastapi/routing.py b/fastapi/routing.py index fa1351859..2e7959f3d 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -454,9 +454,9 @@ class APIRoute(routing.Route): methods = ["GET"] self.methods: Set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): - current_generate_unique_id: Callable[ - ["APIRoute"], str - ] = generate_unique_id_function.value + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) @@ -482,9 +482,9 @@ class APIRoute(routing.Route): # By being a new field, no inheritance will be passed as is. A new model # will always be created. # TODO: remove when deprecating Pydantic v1 - self.secure_cloned_response_field: Optional[ - ModelField - ] = create_cloned_field(self.response_field) + self.secure_cloned_response_field: Optional[ModelField] = ( + create_cloned_field(self.response_field) + ) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None diff --git a/fastapi/utils.py b/fastapi/utils.py index dfda4e678..5c2538fac 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -34,9 +34,9 @@ if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` -_CLONED_TYPES_CACHE: MutableMapping[ - Type[BaseModel], Type[BaseModel] -] = WeakKeyDictionary() +_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( + WeakKeyDictionary() +) def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: diff --git a/requirements-tests.txt b/requirements-tests.txt index 801cf9dd4..08561d23a 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.2.0 +ruff ==0.6.1 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 008dab7bc..039c423b9 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -196,9 +196,9 @@ async def get_sync_context_b_bg( tasks: BackgroundTasks, state: dict = Depends(context_b) ): async def bg(state: dict): - state[ - "sync_bg" - ] = f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + state["sync_bg"] = ( + f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + ) tasks.add_task(bg, state) return state diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py index 42b249211..fe9350f4e 100644 --- a/tests/test_inherited_custom_class.py +++ b/tests/test_inherited_custom_class.py @@ -36,7 +36,7 @@ def test_pydanticv2(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} @@ -79,7 +79,7 @@ def test_pydanticv1(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} From 980c88c347cbb54c72b31491efbdc000788bebbe Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 04:14:10 +0000 Subject: [PATCH 109/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd70a80ff..3c9f53d4b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). From 659350e9cd0e1948ce2bdc95cc3ac2ffb5a41238 Mon Sep 17 00:00:00 2001 From: Jamie Phan Date: Sat, 17 Aug 2024 14:52:31 +1000 Subject: [PATCH 110/356] =?UTF-8?q?=F0=9F=8E=A8=20Fix=20typing=20annotatio?= =?UTF-8?q?n=20for=20semi-internal=20`FastAPI.add=5Fapi=5Froute()`=20(#102?= =?UTF-8?q?40)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/applications.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 4f5e6f1d9..6d427cdc2 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -1056,7 +1056,7 @@ class FastAPI(Starlette): def add_api_route( self, path: str, - endpoint: Callable[..., Coroutine[Any, Any, Response]], + endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: Optional[int] = None, From 6aa0435a3ee1ace6c4fb121a3865c23d2d07bea8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 04:52:53 +0000 Subject: [PATCH 111/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3c9f53d4b..8e58ecb39 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie). * ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo). ### Docs From ff1118d6a0232d3c768a8fe9346d99a004269eef Mon Sep 17 00:00:00 2001 From: Ahsan Sheraz Date: Sat, 17 Aug 2024 08:42:07 +0200 Subject: [PATCH 112/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20Urdu=20translat?= =?UTF-8?q?ion=20for=20`docs/ur/docs/benchmarks.md`=20(#10046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ur/docs/benchmarks.md | 43 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md index 9fc793e6f..8d583de2f 100644 --- a/docs/ur/docs/benchmarks.md +++ b/docs/ur/docs/benchmarks.md @@ -1,5 +1,4 @@ # بینچ مارکس - انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*) لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے. @@ -14,39 +13,39 @@ درجہ بندی کی طرح ہے: -
    -
  • ASGI :Uvicorn سرور
  • +
      +
    • سرور ASGI :Uvicorn
      • -
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
      • +
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
        • -
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
        • +
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
    -
      -
    • Uvicorn:
    • +
        +
      • Uvicorn:
        • -
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • -
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • -
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
        • +
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • +
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • +
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
      -
        -
      • Starlette:
      • +
          +
        • Starlette:
          • -
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • -
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔
          • -
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
          • +
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • +
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔>
          • +
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
        -
          -
        • FastAPI:
        • +
            +
          • FastAPI:
            • -
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • -
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • -
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • -
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )
            • -
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
            • +
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • +
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • +
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • +
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )>
            • +
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
          From 066ea10ac5950ffa941e94ed13f112ceab7ae683 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 06:42:28 +0000 Subject: [PATCH 113/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8e58ecb39..486531569 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,10 @@ hide: * 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo). * 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen). +### Translations + +* 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). + ### Internal * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). From 85cded53c8273cb26ee50089383498422d75f658 Mon Sep 17 00:00:00 2001 From: 0shah0 <84684114+0shah0@users.noreply.github.com> Date: Sat, 17 Aug 2024 12:23:52 +0530 Subject: [PATCH 114/356] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20import=20typ?= =?UTF-8?q?o=20in=20reference=20example=20for=20`Security`=20(#11168)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/param_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 3b25d774a..0d5f27af4 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -2343,7 +2343,7 @@ def Security( # noqa: N802 ```python from typing import Annotated - from fastapi import Depends, FastAPI + from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user From 882f77f9258c45c5962e0b263c63bdfa80eb4fc3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 06:54:13 +0000 Subject: [PATCH 115/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 486531569..17a24a984 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). * 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo). From 9bfc48ad9fba044462eb9d0e1b556cf721f56ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 17 Aug 2024 16:20:31 -0500 Subject: [PATCH 116/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e,=20do=20not=20translate=20to=20have=20the=20most=20recent=20i?= =?UTF-8?q?nfo=20(#12034)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/az/docs/fastapi-people.md | 185 --------------------- docs/de/docs/fastapi-people.md | 176 -------------------- docs/em/docs/fastapi-people.md | 183 --------------------- docs/en/data/members.yml | 12 +- docs/fr/docs/fastapi-people.md | 180 --------------------- docs/ja/docs/fastapi-people.md | 184 --------------------- docs/pl/docs/fastapi-people.md | 178 --------------------- docs/pt/docs/fastapi-people.md | 183 --------------------- docs/ru/docs/fastapi-people.md | 184 --------------------- docs/tr/docs/fastapi-people.md | 183 --------------------- docs/uk/docs/fastapi-people.md | 183 --------------------- docs/zh-hant/docs/fastapi-people.md | 239 ---------------------------- docs/zh/docs/fastapi-people.md | 239 ---------------------------- scripts/docs.py | 1 + scripts/mkdocs_hooks.py | 1 + 15 files changed, 8 insertions(+), 2303 deletions(-) delete mode 100644 docs/az/docs/fastapi-people.md delete mode 100644 docs/de/docs/fastapi-people.md delete mode 100644 docs/em/docs/fastapi-people.md delete mode 100644 docs/fr/docs/fastapi-people.md delete mode 100644 docs/ja/docs/fastapi-people.md delete mode 100644 docs/pl/docs/fastapi-people.md delete mode 100644 docs/pt/docs/fastapi-people.md delete mode 100644 docs/ru/docs/fastapi-people.md delete mode 100644 docs/tr/docs/fastapi-people.md delete mode 100644 docs/uk/docs/fastapi-people.md delete mode 100644 docs/zh-hant/docs/fastapi-people.md delete mode 100644 docs/zh/docs/fastapi-people.md diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md deleted file mode 100644 index 9bb7ad6ea..000000000 --- a/docs/az/docs/fastapi-people.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI İnsanlar - -FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. - - - -## Yaradıcı - İcraçı - -Salam! 👋 - -Bu mənəm: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Cavablar: {{ user.answers }}
          Pull Request-lər: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. - -...Burada isə sizə icmanı göstərmək istəyirəm. - ---- - -**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. - -Bu insanlar: - -* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. - -Bu insanlara təşəkkür edirəm. 👏 🙇 - -## Keçən ayın ən fəal istifadəçiləri - -Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Cavablandırılmış suallar: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Mütəxəssislər - -Burada **FastAPI Mütəxəssisləri** var. 🤓 - -Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. - -Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Cavablandırılmış suallar: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Ən yaxşı əməkdaşlar - -Burada **Ən yaxşı əməkdaşlar** var. 👷 - -Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. - -Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Request-lər: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları FastAPI GitHub Əməkdaşlar səhifəsində görə bilərsiniz. 👷 - -## Ən çox rəy verənlər - -Bu istifadəçilər **ən çox rəy verənlər**dir. - -### Tərcümələr üçün rəylər - -Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. - ---- - -Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Rəylər: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsorlar - -Bunlar **Sponsorlar**dır. 😎 - -Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Qızıl Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bürünc Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Fərdi Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## Məlumatlar haqqında - texniki detallar - -Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. - -Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. - -Bu səhifənin məlumatları hər ay hesablanır və siz buradan mənbə kodunu oxuya bilərsiniz. - -Burada sponsorların əməyini də vurğulamaq istəyirəm. - -Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md deleted file mode 100644 index deaecf214..000000000 --- a/docs/de/docs/fastapi-people.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Leute - -FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. - -## Erfinder - Betreuer - -Hey! 👋 - -Das bin ich: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Answers: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. - -... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. - ---- - -**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. - -Das sind die Menschen, die: - -* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. -* [Pull Requests erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. -* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. - -Eine Runde Applaus für sie. 👏 🙇 - -## Aktivste Benutzer im letzten Monat - -Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ - -{% if people %} -
          -{% for user in people.last_month_active %} - -
          @{{ user.login }}
          Fragen beantwortet: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Experten - -Hier die **FastAPI-Experten**. 🤓 - -Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. - -Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ - -{% if people %} -
          -{% for user in people.experts %} - -
          @{{ user.login }}
          Fragen beantwortet: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Top-Mitwirkende - -Hier sind die **Top-Mitwirkenden**. 👷 - -Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *gemerged* wurden. - -Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 - -{% if people %} -
          -{% for user in people.top_contributors %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der FastAPI GitHub Contributors-Seite sehen. 👷 - -## Top-Rezensenten - -Diese Benutzer sind die **Top-Rezensenten**. 🕵️ - -### Rezensionen für Übersetzungen - -Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. - ---- - -Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. - -{% if people %} -
          -{% for user in people.top_reviewers %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsoren - -Dies sind die **Sponsoren**. 😎 - -Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch GitHub-Sponsoren. - -### Gold Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -### Silber Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if people %} -{% if people.sponsors_50 %} - -### Bronze Sponsoren - -
          -{% for user in people.sponsors_50 %} - - -{% endfor %} - -
          - -{% endif %} -{% endif %} - -### Individuelle Sponsoren - -{% if people %} -
          -{% for user in people.sponsors %} - - -{% endfor %} - -
          -{% endif %} - -## Über diese Daten - technische Details - -Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. - -Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. - -Diese Daten werden jeden Monat berechnet, Sie können den Quellcode hier lesen. - -Hier weise ich auch auf Beiträge von Sponsoren hin. - -Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md deleted file mode 100644 index 75880e216..000000000 --- a/docs/em/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 👫👫 - -FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. - -## 👼 - 🐛 - -🙋 ❗ 👶 - -👉 👤: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          ❔: {{ user.answers }}
          🚲 📨: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#_3){.internal-link target=_blank}. - -...✋️ 📥 👤 💚 🎦 👆 👪. - ---- - -**FastAPI** 📨 📚 🐕‍🦺 ⚪️➡️ 👪. & 👤 💚 🎦 👫 💰. - -👫 👫👫 👈: - -* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank}. -* [✍ 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank}. -* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#_9){.internal-link target=_blank}. - -👏 👫. 👶 👶 - -## 🌅 🦁 👩‍💻 🏁 🗓️ - -👫 👩‍💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          ❔ 📨: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 🕴 - -📥 **FastAPI 🕴**. 👶 - -👫 👩‍💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} 🔘 *🌐 🕰*. - -👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶 - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          ❔ 📨: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 🔝 👨‍🔬 - -📥 **🔝 👨‍🔬**. 👶 - -👉 👩‍💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank} 👈 ✔️ *🔗*. - -👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          🚲 📨: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -📤 📚 🎏 👨‍🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 FastAPI 📂 👨‍🔬 📃. 👶 - -## 🔝 👨‍🔬 - -👫 👩‍💻 **🔝 👨‍🔬**. 👶 👶 - -### 📄 ✍ - -👤 🕴 💬 👩‍❤‍👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨‍🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#_9){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. - ---- - -**🔝 👨‍🔬** 👶 👶 ✔️ 📄 🏆 🚲 📨 ⚪️➡️ 🎏, 🚚 🔆 📟, 🧾, & ✴️, **✍**. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          📄: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 💰 - -👫 **💰**. 👶 - -👫 🔗 👇 👷 ⏮️ **FastAPI** (& 🎏), ✴️ 🔘 📂 💰. - -{% if sponsors %} - -{% if sponsors.gold %} - -### 🌟 💰 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 🥇1st 💰 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 🥈2nd 💰 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 🎯 💰 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## 🔃 📊 - 📡 ℹ - -👑 🎯 👉 📃 🎦 🎯 👪 ℹ 🎏. - -✴️ ✅ 🎯 👈 🛎 🌘 ⭐, & 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ & ⚖ 🚲 📨 ⏮️ ✍. - -💽 ⚖ 🔠 🗓️, 👆 💪 ✍ ℹ 📟 📥. - -📥 👤 🎦 💰 ⚪️➡️ 💰. - -👤 🏦 ▶️️ ℹ 📊, 📄, ⚡, ♒️ (💼 🤷). diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index 0b9e7b94c..0069f8c75 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -1,19 +1,19 @@ members: - login: tiangolo - avatar_url: https://github.com/tiangolo.png + avatar_url: https://avatars.githubusercontent.com/u/1326112 url: https://github.com/tiangolo - login: Kludex - avatar_url: https://github.com/Kludex.png + avatar_url: https://avatars.githubusercontent.com/u/7353520 url: https://github.com/Kludex - login: alejsdev - avatar_url: https://github.com/alejsdev.png + avatar_url: https://avatars.githubusercontent.com/u/90076947 url: https://github.com/alejsdev - login: svlandeg - avatar_url: https://github.com/svlandeg.png + avatar_url: https://avatars.githubusercontent.com/u/8796347 url: https://github.com/svlandeg - login: estebanx64 - avatar_url: https://github.com/estebanx64.png + avatar_url: https://avatars.githubusercontent.com/u/10840422 url: https://github.com/estebanx64 - login: patrick91 - avatar_url: https://github.com/patrick91.png + avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md deleted file mode 100644 index 52a79032a..000000000 --- a/docs/fr/docs/fastapi-people.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -hide: - - navigation ---- - -# La communauté FastAPI - -FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. - -## Créateur - Mainteneur - -Salut! 👋 - -C'est moi : - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Réponses: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#se-rapprocher-de-lauteur){.internal-link target=_blank}. - -...Mais ici, je veux vous montrer la communauté. - ---- - -**FastAPI** reçoit beaucoup de soutien de la part de la communauté. Et je tiens à souligner leurs contributions. - -Ce sont ces personnes qui : - -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#traductions){.internal-link target=_blank}. - -Une salve d'applaudissements pour eux. 👏 🙇 - -## Utilisateurs les plus actifs le mois dernier - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} au cours du dernier mois. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Questions répondues: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Experts - -Voici les **Experts FastAPI**. 🤓 - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} depuis *toujours*. - -Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Questions répondues: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Principaux contributeurs - -Ces utilisateurs sont les **Principaux contributeurs**. 👷 - -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank} qui ont été *merged*. - -Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la Page des contributeurs de FastAPI GitHub. 👷 - -## Principaux Reviewers - -Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ - -### Reviewers des traductions - -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#traductions){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. - ---- - -Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demandes Pull Request des autres, assurant la qualité du code, de la documentation, et surtout, des **traductions**. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsors - -Ce sont les **Sponsors**. 😎 - -Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## À propos des données - détails techniques - -L'intention de cette page est de souligner l'effort de la communauté pour aider les autres. - -Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. - -Les données sont calculées chaque mois, vous pouvez lire le code source ici. - -Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md deleted file mode 100644 index aaf76ba21..000000000 --- a/docs/ja/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI People - -FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 - -## Creator - Maintainer - -こんにちは! 👋 - -これが私です: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Answers: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          - -{% endif %} - -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#_1){.internal-link target=_blank} に記載しています。 - -...ところで、ここではコミュニティを紹介したいと思います。 - ---- - -**FastAPI** は、コミュニティから多くのサポートを受けています。そこで、彼らの貢献にスポットライトを当てたいと思います。 - -紹介するのは次のような人々です: - -* [GitHub issuesで他の人を助ける](help-fastapi.md#github-issues){.internal-link target=_blank}。 -* [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#_8){.internal-link target=_blank})。 - -彼らに大きな拍手を。👏 🙇 - -## 先月最もアクティブだったユーザー - -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Experts - -**FastAPI experts** を紹介します。🤓 - -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。 - -多くの人を助けることでexpertsであると示されています。✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Top Contributors - -**Top Contributors** を紹介します。👷 - -彼らは、*マージされた* [最も多くのプルリクエストを作成した](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}ユーザーです。 - -ソースコード、ドキュメント、翻訳などに貢献してくれました。📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -他にもたくさん (100人以上) の contributors がいます。FastAPI GitHub Contributors ページですべての contributors を確認できます。👷 - -## Top Reviewers - -以下のユーザーは **Top Reviewers** です。🕵️ - -### 翻訳のレビュー - -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#_8){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 - ---- - -**Top Reviewers** 🕵️は、他の人からのプルリクエストのほとんどをレビューし、コード、ドキュメント、特に**翻訳**の品質を保証しています。 - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsors - -**Sponsors** を紹介します。😎 - -彼らは、GitHub Sponsors を介して私の **FastAPI** などに関する活動を支援してくれています。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## データについて - 技術詳細 - -このページの目的は、他の人を助けるためのコミュニティの努力にスポットライトを当てるためです。 - -特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 - -データは毎月集計されます。ソースコードはこちらで確認できます。 - -ここでは、スポンサーの貢献も強調しています。 - -アルゴリズム、セクション、閾値などは更新されるかもしれません (念のために 🤷)。 diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md deleted file mode 100644 index 6c431b401..000000000 --- a/docs/pl/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Ludzie FastAPI - -FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska. - -## Twórca - Opienik - -Cześć! 👋 - -To ja: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Liczba odpowiedzi: {{ user.answers }}
          Pull Requesty: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Ale tutaj chcę pokazać Ci społeczność. - ---- - -**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład. - -To są ludzie, którzy: - -* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}. - -Proszę o brawa dla nich. 👏 🙇 - -## Najaktywniejsi użytkownicy w zeszłym miesiącu - -Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕ - -{% if people %} -
          -{% for user in people.last_month_active %} - -
          @{{ user.login }}
          Udzielonych odpowiedzi: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Eksperci - -Oto **eksperci FastAPI**. 🤓 - -To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*. - -Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨ - -{% if people %} -
          -{% for user in people.experts %} - -
          @{{ user.login }}
          Udzielonych odpowiedzi: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Najlepsi Kontrybutorzy - -Oto **Najlepsi Kontrybutorzy**. 👷 - -Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*. - -Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 - -{% if people %} -
          -{% for user in people.top_contributors %} - -
          @{{ user.login }}
          Pull Requesty: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie Kontrybutorzy FastAPI na GitHub. 👷 - -## Najlepsi Oceniajacy - -Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️ - -### Oceny Tłumaczeń - -Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach. - ---- - -**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**. - -{% if people %} -
          -{% for user in people.top_reviewers %} - -
          @{{ user.login }}
          Liczba ocen: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsorzy - -Oto **Sponsorzy**. 😎 - -Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Złoci Sponsorzy - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Srebrni Sponsorzy - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Brązowi Sponsorzy - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Indywidualni Sponsorzy - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## Techniczne szczegóły danych - -Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym. - -Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. - -Dane są obliczane każdego miesiąca, możesz przeczytać kod źródłowy tutaj. - -Tutaj również podkreślam wkład od sponsorów. - -Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷). diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md deleted file mode 100644 index d67ae0d33..000000000 --- a/docs/pt/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Pessoas do FastAPI - -FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. - -## Criador - Mantenedor - -Ei! 👋 - -Este sou eu: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Respostas: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#conect-se-com-o-autor){.internal-link target=_blank}. - -...Mas aqui eu quero mostrar a você a comunidade. - ---- - -**FastAPI** recebe muito suporte da comunidade. E quero destacar suas contribuições. - -Estas são as pessoas que: - -* [Help others with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#traducoes){.internal-link target=_blank}. - -Uma salva de palmas para eles. 👏 🙇 - -## Usuários mais ativos do ultimo mês - -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} durante o ultimo mês. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Issues respondidas: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Especialistas - -Aqui está os **Especialistas do FastAPI**. 🤓 - - -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} em *todo o tempo*. - -Eles provaram ser especialistas ajudando muitos outros. ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Issues respondidas: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Top Contribuidores - -Aqui está os **Top Contribuidores**. 👷 - -Esses usuários têm [created the most Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank} que tem sido *mergeado*. - -Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em Página de Contribuidores do FastAPI no GitHub. 👷 - -## Top Revisores - -Esses usuários são os **Top Revisores**. 🕵️ - -### Revisões para Traduções - -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#traducoes){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. - ---- - -Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, garantindo a qualidade do código, documentação, e especialmente, as **traduções**. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Revisões: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Patrocinadores - -Esses são os **Patrocinadores**. 😎 - -Eles estão apoiando meu trabalho **FastAPI** (e outros), principalmente através de GitHub Sponsors. - -{% if sponsors %} -{% if sponsors.gold %} - -### Patrocinadores Ouro - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Patrocinadores Prata - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Patrocinadores Bronze - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -### Patrocinadores Individuais - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -{% endif %} - -## Sobre os dados - detalhes técnicos - -A principal intenção desta página é destacar o esforço da comunidade para ajudar os outros. - -Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. - -Os dados são calculados todo mês, você pode ler o código fonte aqui. - -Aqui também estou destacando contribuições de patrocinadores. - -Eu também me reservo o direito de atualizar o algoritmo, seções, limites, etc (só para prevenir 🤷). diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md deleted file mode 100644 index 31bb2798e..000000000 --- a/docs/ru/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди, поддерживающие FastAPI - -У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний. - -## Создатель и хранитель - -Хай! 👋 - -Это я: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Answers: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#_2){.internal-link target=_blank}. - -... но на этой странице я хочу показать вам наше сообщество. - ---- - -**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников. - -Это люди, которые: - -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#-_1){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#_8){.internal-link target=_blank}. - -Поаплодируем им! 👏 🙇 - -## Самые активные участники за прошедший месяц - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} в течение последнего месяца. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Эксперты - -Здесь представлены **Эксперты FastAPI**. 🤓 - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} за *всё время*. - -Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Рейтинг участников, внёсших вклад в код - -Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 - -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#-_1){.internal-link target=_blank}, *включённых в основной код*. - -Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице FastAPI GitHub Contributors page. 👷 - -## Рейтинг ревьюеров - -Здесь представлен **Рейтинг ревьюеров**. 🕵️ - -### Проверки переводов на другие языки - -Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#_8){.internal-link target=_blank}. Без них не было бы документации на многих языках. - ---- - -В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Спонсоры - -Здесь представлены **Спонсоры**. 😎 - -Спонсоры поддерживают мою работу над **FastAPI** (и другими проектами) главным образом через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золотые спонсоры - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Серебрянные спонсоры - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзовые спонсоры - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Индивидуальные спонсоры - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## О данных - технические детали - -Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим. - -Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. - -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно тут. - -Кроме того, я также подчеркиваю вклад спонсоров. - -И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷). diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md deleted file mode 100644 index de62c57c4..000000000 --- a/docs/tr/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Topluluğu - -FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. - -## Yazan - Geliştiren - -Merhaba! 👋 - -İşte bu benim: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Cevaplar: {{ user.answers }}
          Pull Request'ler: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Ben **FastAPI**'ın geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: [FastAPI yardım - yardım al - benimle iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...burada size harika FastAPI topluluğunu göstermek istiyorum. - ---- - -**FastAPI**, topluluğundan çok destek alıyor. Ben de onların katkılarını vurgulamak istiyorum. - -Bu insanlar: - -* [GitHubdaki soruları cevaplayarak diğerlerine yardım ediyor](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request'ler oluşturuyor](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request'leri gözden geçiriyorlar, [özellikle çeviriler için bu çok önemli](contributing.md#translations){.internal-link target=_blank}. - -Onları bir alkışlayalım. 👏 🙇 - -## Geçen Ayın En Aktif Kullanıcıları - -Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} kullanıcılar. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Cevaplanan soru sayısı: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Uzmanlar - -İşte **FastAPI Uzmanları**. 🤓 - -Uzmanlarımız ise *tüm zamanlar boyunca* [GitHub'da insanların sorularına en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} insanlar. - -Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Cevaplanan soru sayısı: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## En Fazla Katkıda Bulunanlar - -Şimdi ise sıra **en fazla katkıda bulunanlar**da. 👷 - -Bu kullanıcılar en fazla [kaynak koduyla birleştirilen Pull Request'lere](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} sahip! - -Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulundular. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Request sayısı: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini FastAPI GitHub Katkıda Bulunanlar sayfasında görebilirsin. 👷 - -## En Fazla Değerlendirme Yapanlar - -İşte **en çok değerlendirme yapanlar**. 🕵️ - -### Çeviri Değerlendirmeleri - -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden değerlendirme yapanların da döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} var. Onlar olmasaydı çeşitli dillerde dökümantasyon da olmazdı. - ---- - -**En fazla değerlendirme yapanlar** 🕵️ kodun, dökümantasyonun ve özellikle **çevirilerin** Pull Request'lerini inceleyerek kalitesinden emin oldular. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Değerlendirme sayısı: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Sponsorlar - -işte **Sponsorlarımız**. 😎 - -Çoğunlukla GitHub Sponsorları aracılığıyla olmak üzere, **FastAPI** ve diğer projelerdeki çalışmalarımı destekliyorlar. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Altın Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronz Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Bireysel Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## Veriler - Teknik detaylar - -Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. - -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. - -Veriler ayda bir hesaplanır, kaynak kodu buradan okuyabilirsin. - -Burada sponsorların katkılarını da vurguluyorum. - -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutuyorum (her ihtimale karşı 🤷). diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md deleted file mode 100644 index c6a6451d8..000000000 --- a/docs/uk/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди FastAPI - -FastAPI має дивовижну спільноту, яка вітає людей різного походження. - -## Творець – Супроводжувач - -Привіт! 👋 - -Це я: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Answers: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -Я - творець і супроводжувач **FastAPI**. Детальніше про це можна прочитати в [Довідка FastAPI - Отримати довідку - Зв'язатися з автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Але тут я хочу показати вам спільноту. - ---- - -**FastAPI** отримує велику підтримку від спільноти. І я хочу відзначити їхній внесок. - -Це люди, які: - -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. - -Оплески їм. 👏 🙇 - -## Найбільш активні користувачі минулого місяця - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Експерти - -Ось **експерти FastAPI**. 🤓 - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом *всього часу*. - -Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          Issues replied: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Найкращі контрибютори - -Ось **Найкращі контрибютори**. 👷 - -Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. - -Вони надали програмний код, документацію, переклади тощо. 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці FastAPI GitHub Contributors. 👷 - -## Найкращі рецензенти - -Ці користувачі є **Найкращими рецензентами**. 🕵️ - -### Рецензенти на переклади - -Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. - ---- - -**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## Спонсори - -Це **Спонсори**. 😎 - -Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золоті спонсори - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Срібні спонсори - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзові спонсори - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Індивідуальні спонсори - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## Про дані - технічні деталі - -Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. - -Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. - -Дані розраховуються щомісяця, ви можете ознайомитися з вихідним кодом тут. - -Тут я також підкреслюю внески спонсорів. - -Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md deleted file mode 100644 index 99277b419..000000000 --- a/docs/zh-hant/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社群 - -FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 - -## 作者 - -嘿! 👋 - -關於我: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          解答問題: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -我是 **FastAPI** 的作者。你可以在[幫助 FastAPI - 獲得幫助 - 與作者聯繫](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 中閱讀更多相關資訊。 - -...但在這裡,我想向你介紹這個社群。 - ---- - -**FastAPI** 獲得了許多社群的大力支持。我想特別表揚他們的貢獻。 - -這些人包括: - -* [在 GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 -* [建立 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 審查 Pull Requests,[尤其是翻譯方面的貢獻](contributing.md#translations){.internal-link target=_blank}。 - -讓我們為他們熱烈鼓掌。 👏 🙇 - -## FastAPI 專家 - -這些是在 [GitHub 中幫助其他人解決問題最多的用戶](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🙇 - -他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ - -/// 提示 - -你也可以成為官方的 FastAPI 專家! - -只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 - -/// - -你可以查看這些期間的 **FastAPI 專家**: - -* [上個月](#fastapi-experts-last-month) 🤓 -* [過去 3 個月](#fastapi-experts-3-months) 😎 -* [過去 6 個月](#fastapi-experts-6-months) 🧐 -* [過去 1 年](#fastapi-experts-1-year) 🧑‍🔬 -* [**所有時間**](#fastapi-experts-all-time) 🧙 - -### FastAPI 專家 - 上個月 - -上個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🤓 - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          回答問題數: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 專家 - 過去 3 個月 - -過去三個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 😎 - -{% if people %} -
          -{% for user in people.three_months_experts[:10] %} - -
          @{{ user.login }}
          回答問題數: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 專家 - 過去 6 個月 - -過去六個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧐 - -{% if people %} -
          -{% for user in people.six_months_experts[:10] %} - -
          @{{ user.login }}
          回答問題數: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 專家 - 過去一年 - -過去一年在 [GitHub 中幫助他人解決最多問題的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧑‍🔬 - -{% if people %} -
          -{% for user in people.one_year_experts[:20] %} - -
          @{{ user.login }}
          回答問題數: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 專家 - 全部時間 - -以下是全部時間的 **FastAPI 專家**。 🤓🤯 - -過去在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧙 - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          回答問題數: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 主要貢獻者 - -以下是**主要貢獻者**。 👷 - -這些用戶[建立了最多已被**合併**的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 - -他們貢獻了原始碼、文件和翻譯等。 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -還有許多其他的貢獻者(超過一百位),你可以在 FastAPI GitHub 貢獻者頁面查看。 👷 - -## 主要翻譯審核者 - -以下是 **主要翻譯審核者**。 🕵️ - -我只會講幾種語言(而且不是很流利 😅),所以審核者[**擁有批准翻譯**](contributing.md#translations){.internal-link target=_blank}文件的權限。沒有他們,就不會有多語言版本的文件。 - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          Reviews: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 贊助者 - -以下是**贊助者**。 😎 - -他們主要透過 GitHub Sponsors 支持我在 **FastAPI**(以及其他項目)上的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌贊助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 銀牌贊助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 銅牌贊助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 個人贊助商 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## 關於數據 - 技術細節 - -這個頁面的主要目的是突顯社群幫助他人所做的努力 - -特別是那些通常不太顯眼但往往更加艱辛的工作,例如幫助他人解答問題和審查包含翻譯的 Pull Requests。 - -這些數據每月計算一次,你可以在這查看原始碼。 - -此外,我也特別表揚贊助者的貢獻。 - -我也保留更新演算法、章節、門檻值等的權利(以防萬一 🤷)。 diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md deleted file mode 100644 index 30a75240c..000000000 --- a/docs/zh/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社区 - -FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 - -## 创建者 & 维护者 - -嘿! 👋 - -这就是我: - -{% if people %} -
          -{% for user in people.maintainers %} - -
          @{{ user.login }}
          Answers: {{ user.answers }}
          Pull Requests: {{ user.prs }}
          -{% endfor %} - -
          -{% endif %} - -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#_2){.internal-link target=_blank} 阅读有关此内容的更多信息。 - -...但是在这里我想向您展示社区。 - ---- - -**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。 - -这些人: - -* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 - -向他们致以掌声。 👏 🙇 - -## FastAPI 专家 - -这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇 - -他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ - -/// 小提示 - -你也可以成为认可的 FastAPI 专家! - -只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 - -/// - -你可以查看不同时期的 **FastAPI 专家**: - -* [上个月](#fastapi-experts-last-month) 🤓 -* [三个月](#fastapi-experts-3-months) 😎 -* [六个月](#fastapi-experts-6-months) 🧐 -* [一年](#fastapi-experts-1-year) 🧑‍🔬 -* [**全部时间**](#fastapi-experts-all-time) 🧙 - -## FastAPI 专家 - 上个月 - -这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓 - -{% if people %} -
          -{% for user in people.last_month_experts[:10] %} - -
          @{{ user.login }}
          回答问题数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 专家 - 三个月 - -这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎 - -{% if people %} -
          -{% for user in people.three_months_experts[:10] %} - -
          @{{ user.login }}
          回答问题数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 专家 - 六个月 - -这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐 - -{% if people %} -
          -{% for user in people.six_months_experts[:10] %} - -
          @{{ user.login }}
          回答问题数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -### FastAPI 专家 - 一年 - -这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑‍🔬 - -{% if people %} -
          -{% for user in people.one_year_experts[:20] %} - -
          @{{ user.login }}
          回答问题数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## FastAPI 专家 - 全部时间 - -以下是全部时间的 **FastAPI 专家**。 🤓🤯 - -这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙 - -{% if people %} -
          -{% for user in people.experts[:50] %} - -
          @{{ user.login }}
          回答问题数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 杰出贡献者 - -以下是 **杰出的贡献者**。 👷 - -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 - -他们贡献了源代码,文档,翻译等。 📦 - -{% if people %} -
          -{% for user in people.top_contributors[:50] %} - -
          @{{ user.login }}
          Pull Requests: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -还有很多别的贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 - -## 杰出翻译审核者 - -以下用户是 **杰出的评审者**。 🕵️ - -我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。 - -{% if people %} -
          -{% for user in people.top_translations_reviewers[:50] %} - -
          @{{ user.login }}
          审核数: {{ user.count }}
          -{% endfor %} - -
          -{% endif %} - -## 赞助商 - -以下是 **赞助商** 。😎 - -他们主要通过GitHub Sponsors支持我在 **FastAPI** (和其他项目)的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌赞助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 银牌赞助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 铜牌赞助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 个人赞助 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
          - -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
          - -{% endfor %} -{% endif %} - -## 关于数据 - 技术细节 - -该页面的目的是突出社区为帮助他人而付出的努力。 - -尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 - -该数据每月计算一次,您可以阅读 源代码。 - -这里也强调了赞助商的贡献。 - -我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。 diff --git a/scripts/docs.py b/scripts/docs.py index 1dba4aa0a..f0c51f7a6 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -29,6 +29,7 @@ missing_translation_snippet = """ non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 10e8dc153..0bc4929a4 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -11,6 +11,7 @@ from mkdocs.structure.pages import Page non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", From 0da0814d8a2029b7d2e19043a606c7faea6b02fa Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 21:20:52 +0000 Subject: [PATCH 117/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 17a24a984..91bbb2adc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Translations +* 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). ### Internal From 4f1eb0cd9e571a68fab19eecbdc59cc27aa7e6f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 16:07:03 -0500 Subject: [PATCH 118/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20coverage=20conf?= =?UTF-8?q?ig=20files=20(#12035)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 2 +- pyproject.toml | 8 ++++++++ scripts/test-cov-html.sh | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a33b6a68a..0458f83ff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -117,7 +117,7 @@ jobs: - run: ls -la coverage - run: coverage combine coverage - run: coverage report - - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" + - run: coverage html --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML uses: actions/upload-artifact@v4 with: diff --git a/pyproject.toml b/pyproject.toml index 8db2d2b2d..bb87be470 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -165,6 +165,7 @@ filterwarnings = [ [tool.coverage.run] parallel = true +data_file = "coverage/.coverage" source = [ "docs_src", "tests", @@ -177,6 +178,13 @@ omit = [ "docs_src/response_model/tutorial003_04_py310.py", ] +[tool.coverage.report] +show_missing = true +sort = "-Cover" + +[tool.coverage.html] +show_contexts = true + [tool.ruff.lint] select = [ "E", # pycodestyle errors diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index 85aef9601..517ac6422 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -5,5 +5,5 @@ set -x bash scripts/test.sh ${@} coverage combine -coverage report --show-missing -coverage html --show-contexts +coverage report +coverage html From 6ebaf0efcb38efc6f06f302fe30142071cfd53e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 21:08:39 +0000 Subject: [PATCH 119/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 91bbb2adc..cb3e8628e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -34,6 +34,7 @@ hide: ### Internal +* 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). From 0e77481acfc5f548cd053ee36dbd2879651d73c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 18:16:56 -0500 Subject: [PATCH 120/356] =?UTF-8?q?=F0=9F=93=9D=20Move=20the=20Features=20?= =?UTF-8?q?docs=20to=20the=20top=20level=20to=20improve=20the=20main=20pag?= =?UTF-8?q?e=20menu=20(#12036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d23ddd42f..d0527ca3c 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -102,9 +102,8 @@ plugins: show_symbol_type_toc: true nav: -- FastAPI: - - index.md - - features.md +- FastAPI: index.md +- features.md - Learn: - learn/index.md - python-types.md From 98712b9e09429e0dd514d39c5064cde4f6ae657b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 23:17:21 +0000 Subject: [PATCH 121/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cb3e8628e..bd8580271 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). From bcd737de33dfb1c1871f86320b12c86158393b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 18:26:14 -0500 Subject: [PATCH 122/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20Asyncer=20mention?= =?UTF-8?q?=20in=20async=20docs=20(#12037)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/async.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 43fd8e70d..7cf4af627 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -369,6 +369,8 @@ In particular, you can directly use AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*). +I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: Asyncer. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code. + ### Other forms of asynchronous code This style of using `async` and `await` is relatively new in the language. From ae97785ded0dfb5128cbd6bb9542eaf0fc44f903 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 23:26:36 +0000 Subject: [PATCH 123/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd8580271..570e7e9db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). From f0866bc2050552621566ca0c0fd111936ac36918 Mon Sep 17 00:00:00 2001 From: xuvjso Date: Tue, 20 Aug 2024 01:35:03 +0800 Subject: [PATCH 124/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20docs=20about=20?= =?UTF-8?q?dependencies=20with=20yield=20(#12028)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 269 +++++++++++++----- 1 file changed, 197 insertions(+), 72 deletions(-) diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index beca95d45..6058f7878 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,12 +1,12 @@ # 使用yield的依赖项 -FastAPI支持在完成后执行一些额外步骤的依赖项. +FastAPI支持在完成后执行一些额外步骤的依赖项. -为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 +为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。 -/// tip | "提示" +/// tip | 提示 -确保只使用一次 `yield` 。 +确保在每个依赖中只使用一次 `yield`。 /// @@ -25,7 +25,7 @@ FastAPI支持在完成后执行一些> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` -/// info +/// info | 说明 -只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 +只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。 在发送了其中一个响应之后,就无法再发送其他响应了。 /// -/// tip +/// tip | 提示 + +这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。 + +如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。 + +/// + +## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务 + +/// warning | 注意 + +你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。 + +如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。 + +/// + +### 包含 `yield` 和 `except` 的依赖项的技术细节 + +在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。 + +### 后台任务和使用 `yield` 的依赖项的技术细节 + +在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。 -这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 +这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。 -如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 +然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。 + +/// tip | 提示 + +除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。 + +这样也会让你的代码更加简洁。 /// +如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。 + +例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。 + ## 上下文管理器 -### 什么是“上下文管理器” +### 什么是"上下文管理器" -“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 +"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。 -例如,您可以使用`with`读取文件: +例如,你可以使用`with`读取文件: ```Python with open("./somefile.txt") as f: @@ -254,38 +379,38 @@ with open("./somefile.txt") as f: print(contents) ``` -在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 +在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。 -当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 +当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。 -当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 +当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 -### 在依赖项中使用带有`yield`的上下文管理器 +### 在使用 `yield` 的依赖项中使用上下文管理器 -/// warning +/// warning | 注意 -这是一个更为“高级”的想法。 +这是一个更为"高级"的想法。 -如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 +如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。 /// 在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 -你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 +你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们: ```Python hl_lines="1-9 13" {!../../../docs_src/dependencies/tutorial010.py!} ``` -/// tip +/// tip | 提示 另一种创建上下文管理器的方法是: * `@contextlib.contextmanager`或者 * `@contextlib.asynccontextmanager` -使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 From 63ae0f1070ba1df314b55e2454ec5e356725bd16 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 19 Aug 2024 17:35:25 +0000 Subject: [PATCH 125/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 570e7e9db..3b41fa2ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 6ba8407ff3acc0e2b8792c35a363803f08c78971 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Mon, 19 Aug 2024 13:15:21 -0500 Subject: [PATCH 126/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20Spanish=20trans?= =?UTF-8?q?lation=20docs=20for=20consistency=20(#12044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/advanced/additional-status-codes.md | 4 ++-- docs/es/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 4 ++-- docs/es/docs/advanced/response-directly.md | 4 ++-- docs/es/docs/advanced/response-headers.md | 2 +- docs/es/docs/advanced/security/index.md | 2 +- docs/es/docs/async.md | 8 ++++---- docs/es/docs/deployment/versions.md | 4 ++-- docs/es/docs/features.md | 2 +- docs/es/docs/how-to/graphql.md | 4 ++-- docs/es/docs/python-types.md | 6 +++--- docs/es/docs/tutorial/cookie-params.md | 16 ++++++++-------- docs/es/docs/tutorial/first-steps.md | 12 ++++++------ docs/es/docs/tutorial/path-params.md | 16 ++++++++-------- docs/es/docs/tutorial/query-params.md | 6 +++--- 15 files changed, 46 insertions(+), 46 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index f40fad03c..664604c59 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "Advertencia" +/// warning | Advertencia Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. @@ -28,7 +28,7 @@ Asegúrate de que la respuesta tenga los datos que quieras, y que los valores se /// -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index 88ef8e19f..10a1ff0d5 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -6,7 +6,7 @@ El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_bl En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. -/// tip +/// tip | Consejo Las próximas secciones **no son necesariamente "avanzadas"**. diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 9e8714fe4..18f96213f 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -26,13 +26,13 @@ Deberías hacerlo después de adicionar todas tus *operaciones de path*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. /// -/// warning | "Advertencia" +/// warning | Advertencia Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 7ce5bddca..4eeab3fd0 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizado De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. -/// tip | "Consejo" +/// tip | Consejo `JSONResponse` en sí misma es una subclase de `Response`. @@ -38,7 +38,7 @@ Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos ante {!../../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También puedes usar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index 414b145fc..c3aa20993 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -29,7 +29,7 @@ Crea un response tal como se describe en [Retornar una respuesta directamente](r {!../../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 7fa8047e9..92de67d6a 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -/// tip +/// tip | Consejo Las siguientes secciones **no necesariamente son "avanzadas"**. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 193d24270..5ab2ff9a4 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "Nota" +/// note | Nota Solo puedes usar `await` dentro de funciones creadas con `async def`. @@ -138,7 +138,7 @@ Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. illustration -/// info +/// info | Información Las ilustraciones fueron creados por Ketrina Thompson. 🎨 @@ -204,7 +204,7 @@ Sólo las comes y listo 🍔 ⏹. No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. -/// info +/// info | Información Las ilustraciones fueron creados por Ketrina Thompson. 🎨 @@ -396,7 +396,7 @@ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que te ## Detalles muy técnicos -/// warning | "Advertencia" +/// warning | Advertencia Probablemente puedas saltarte esto. diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index 7d09a2739..74243da89 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -42,7 +42,7 @@ Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por deba FastAPI también sigue la convención de que cualquier cambio hecho en una "PATCH" version es para solucionar errores y *non-breaking changes*. -/// tip +/// tip | Consejo El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 En versiones "MINOR" son añadidas nuevas características y posibles breaking changes. -/// tip +/// tip | Consejo La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 3c610f8f1..b75918dff 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info +/// info | Información `**second_user_data` significa: diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index d75af7d81..590c2e828 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -4,7 +4,7 @@ Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar c Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. -/// tip +/// tip | Consejo **GraphQL** resuelve algunos casos de uso específicos. @@ -49,7 +49,7 @@ Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a starlette-graphene3, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** -/// tip +/// tip | Consejo Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index fce434483..4015dbb05 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,7 +12,7 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -/// note | "Nota" +/// note | Nota Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. @@ -256,7 +256,7 @@ Tomado de la documentación oficial de Pydantic: {!../../../docs_src/python_types/tutorial010.py!} ``` -/// info | "Información" +/// info | Información Para aprender más sobre Pydantic mira su documentación. @@ -288,7 +288,7 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -/// info | "Información" +/// info | Información Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 27ba8ed57..3eaea31f9 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -32,9 +32,9 @@ Primero importa `Cookie`: //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -46,9 +46,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -90,9 +90,9 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -104,9 +104,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index affdfebff..8d8909b97 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "Nota" +/// note | Nota El comando `uvicorn main:app` se refiere a: @@ -139,7 +139,7 @@ También podrías usarlo para generar código automáticamente, para los cliente `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos `FastAPI` es una clase que hereda directamente de `Starlette`. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Información" +/// info | Información Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". @@ -259,7 +259,7 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una operación get -/// info | "Información sobre `@decorator`" +/// info | Información sobre `@decorator` Esa sintaxis `@algo` se llama un "decorador" en Python. @@ -286,7 +286,7 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -/// tip | "Consejo" +/// tip | Consejo Tienes la libertad de usar cada operación (método de HTTP) como quieras. @@ -324,7 +324,7 @@ También podrías definirla como una función estándar en lugar de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Nota" +/// note | Nota Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 73bd586f1..e09e0381f 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. -/// check | "Revisa" +/// check | Revisa Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. @@ -38,7 +38,7 @@ Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/4.2 -/// check | "Revisa" +/// check | Revisa Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. @@ -85,7 +85,7 @@ Cuando abras tu navegador en -/// check | "Revisa" +/// check | Revisa Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) @@ -143,13 +143,13 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib {!../../../docs_src/path_params/tutorial005.py!} ``` -/// info | "Información" +/// info | Información Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. /// -/// tip | "Consejo" +/// tip | Consejo Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. @@ -189,7 +189,7 @@ Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value` {!../../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Consejo" +/// tip | Consejo También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. @@ -246,7 +246,7 @@ Entonces lo puedes usar con: {!../../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 52a3e66a4..6f88fd617 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -69,13 +69,13 @@ Del mismo modo puedes declarar parámetros de query opcionales definiendo el val En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -/// check | "Revisa" +/// check | Revisa También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. /// -/// note | "Nota" +/// note | Nota FastAPI sabrá que `q` es opcional por el `= None`. @@ -199,7 +199,7 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -/// tip | "Consejo" +/// tip | Consejo También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. From e8322228b42c11299d1df75bf3586a3a675f72d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 19 Aug 2024 18:15:49 +0000 Subject: [PATCH 127/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3b41fa2ad..646060fea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From f4dfbae90396c1eed349fa96e1770874fe482ae1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 19:40:31 -0500 Subject: [PATCH 128/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.6.0) - https://github.com/charliermarsh/ruff-pre-commit → https://github.com/astral-sh/ruff-pre-commit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1ed005657..7532f21b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.6.0 hooks: - id: check-added-large-files - id: check-toml @@ -13,7 +13,7 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/charliermarsh/ruff-pre-commit +- repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.1 hooks: - id: ruff From 2d34086b70a1026aeb4974ffcf92041cd69e1ece Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 20 Aug 2024 00:40:55 +0000 Subject: [PATCH 129/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 646060fea..f562ba06e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12046](https://github.com/fastapi/fastapi/pull/12046) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). From 34e6e63fb2ca05a5929bc2d151b4e45194ed87a0 Mon Sep 17 00:00:00 2001 From: Yuki Watanabe Date: Thu, 22 Aug 2024 01:55:16 +0900 Subject: [PATCH 130/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/learn/index.md`=20(#11592)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/ja/docs/learn/index.md diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md new file mode 100644 index 000000000..2f24c670a --- /dev/null +++ b/docs/ja/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学習 + +ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。 + +これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎 From 2fe05762b2672959d754ee869a11efbf9cdd6e97 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 21 Aug 2024 16:55:38 +0000 Subject: [PATCH 131/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f562ba06e..a9fcd1383 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). From 38ff43b690df0d5a8ce7e4069750696eca323c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Wed, 21 Aug 2024 13:56:50 -0300 Subject: [PATCH 132/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/request=5Ffile.md`=20(#12?= =?UTF-8?q?018)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request_files.md | 418 +++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 docs/pt/docs/tutorial/request_files.md diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md new file mode 100644 index 000000000..60e4ecb26 --- /dev/null +++ b/docs/pt/docs/tutorial/request_files.md @@ -0,0 +1,418 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados para o cliente utilizando `File`. + +/// info + +Para receber arquivos compartilhados, primeiro instale `python-multipart`. + +E.g. `pip install python-multipart`. + +Isso se deve por que arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` do `fastapi`: + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +## Defina os parâmetros de `File` + +Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição. + +/// + +Os arquivos serão enviados como "form data". + +Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`. + +Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos. + +Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. + +## Parâmetros de arquivo com `UploadFile` + +Defina um parâmetro de arquivo com o tipo `UploadFile` + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +Utilizando `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar `File()` como o valor padrão do parâmetro. +* A classe utiliza um arquivo em "spool": + * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco. +* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória. +* Você pode obter metadados do arquivo enviado. +* Ela possui uma interface semelhante a arquivos `async`. +* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo. + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`). +* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`). +* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like". + +`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno). + +* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo. +* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`). +* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo. + * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles. + +Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes técnicos do `async` + +Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles. + +/// + +/// note | Detalhes técnicos do Starlette + +O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic** + +/// + +## O que é "Form Data" + +A forma como formulários HTML(`
          `) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON. + +O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON. + +/// note | Detalhes Técnicos + +Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos. + +Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição. + +Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST . + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`. + +Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. + +/// + +## Arquivo de upload opcional + +Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: + +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// + +## `UploadFile` com Metadados Adicionais + +Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` + +//// + +## Envio de Múltiplos Arquivos + +É possível enviar múltiplos arquivos ao mesmo tmepo. + +Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// + +Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, + +/// note | Detalhes Técnicos + +Você também poderia utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette. + +/// + +### Enviando Múltiplos Arquivos com Metadados Adicionais + +E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` + +//// + +## Recapitulando + +Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário. From 4f3381a95eee1c1a76630d0a232cdd4553166d2b Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 21 Aug 2024 16:58:20 +0000 Subject: [PATCH 133/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a9fcd1383..12f1f50cd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). From 705659bb2277633e75269de9bac9d84cc3c15ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 21 Aug 2024 19:47:31 -0500 Subject: [PATCH 134/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs=20about=20Env?= =?UTF-8?q?ironment=20Variables=20and=20Virtual=20Environments=20(#12054)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + docs/en/docs/advanced/settings.md | 126 +-- docs/en/docs/advanced/templates.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/contributing.md | 138 +-- docs/en/docs/deployment/manually.md | 4 +- docs/en/docs/deployment/server-workers.md | 2 + docs/en/docs/environment-variables.md | 300 +++++++ docs/en/docs/index.md | 2 + docs/en/docs/tutorial/index.md | 8 +- docs/en/docs/tutorial/request-files.md | 6 +- .../docs/tutorial/request-forms-and-files.md | 6 +- docs/en/docs/tutorial/request-forms.md | 6 +- docs/en/docs/tutorial/response-model.md | 13 +- docs/en/docs/tutorial/security/first-steps.md | 8 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 6 +- docs/en/docs/tutorial/sql-databases.md | 4 +- docs/en/docs/tutorial/testing.md | 10 +- docs/en/docs/virtual-environments.md | 844 ++++++++++++++++++ docs/en/mkdocs.yml | 2 + 20 files changed, 1228 insertions(+), 263 deletions(-) create mode 100644 docs/en/docs/environment-variables.md create mode 100644 docs/en/docs/virtual-environments.md diff --git a/README.md b/README.md index b00ef6ba9..889a89ed7 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a virtual environment and then install FastAPI: +
          ```console diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index b78f83953..22bf7de20 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -6,135 +6,17 @@ Most of these settings are variable (can change), like database URLs. And many c For this reason it's common to provide them in environment variables that are read by the application. -## Environment Variables - -/// tip - -If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. - -/// - -An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). - -You can create and use environment variables in the shell, without needing Python: - -//// tab | Linux, macOS, Windows Bash - -
          - -```console -// You could create an env var MY_NAME with -$ export MY_NAME="Wade Wilson" - -// Then you could use it with other programs, like -$ echo "Hello $MY_NAME" - -Hello Wade Wilson -``` - -
          - -//// - -//// tab | Windows PowerShell - -
          - -```console -// Create an env var MY_NAME -$ $Env:MY_NAME = "Wade Wilson" - -// Use it with other programs, like -$ echo "Hello $Env:MY_NAME" - -Hello Wade Wilson -``` - -
          - -//// - -### Read env vars in Python - -You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. - -For example you could have a file `main.py` with: - -```Python hl_lines="3" -import os - -name = os.getenv("MY_NAME", "World") -print(f"Hello {name} from Python") -``` - -/// tip - -The second argument to `os.getenv()` is the default value to return. - -If not provided, it's `None` by default, here we provide `"World"` as the default value to use. - -/// - -Then you could call that Python program: - -
          - -```console -// Here we don't set the env var yet -$ python main.py - -// As we didn't set the env var, we get the default value - -Hello World from Python - -// But if we create an environment variable first -$ export MY_NAME="Wade Wilson" - -// And then call the program again -$ python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python -``` - -
          - -As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. - -You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. - -To do that, create it right before the program itself, on the same line: - -
          - -```console -// Create an env var MY_NAME in line for this program call -$ MY_NAME="Wade Wilson" python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python - -// The env var no longer exists afterwards -$ python main.py - -Hello World from Python -``` - -
          - /// tip -You can read more about it at The Twelve-Factor App: Config. +To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}. /// -### Types and validation +## Types and validation These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). -That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code. ## Pydantic `Settings` @@ -142,7 +24,7 @@ Fortunately, Pydantic provides a great utility to handle these settings coming f ### Install `pydantic-settings` -First, install the `pydantic-settings` package: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
          diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 43731ec36..416540ba4 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F ## Install dependencies -Install `jinja2`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
          diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 9655714b0..44c6c7428 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -4,7 +4,7 @@ You can use diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 63e1f359a..91d5724a8 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -6,117 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. -### Virtual environment with `venv` +### Virtual environment -You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is): - -
          - -```console -$ python -m venv env -``` - -
          - -That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. - -### Activate the environment - -Activate the new environment with: - -//// tab | Linux, macOS - -
          - -```console -$ source ./env/bin/activate -``` - -
          - -//// - -//// tab | Windows PowerShell - -
          - -```console -$ .\env\Scripts\Activate.ps1 -``` - -
          - -//// - -//// tab | Windows Bash - -Or if you use Bash for Windows (e.g. Git Bash): - -
          - -```console -$ source ./env/Scripts/activate -``` - -
          - -//// - -To check it worked, use: - -//// tab | Linux, macOS, Windows Bash - -
          - -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
          - -//// - -//// tab | Windows PowerShell - -
          - -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
          - -//// - -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Make sure you have the latest pip version on your local environment to avoid errors on the next steps: - -
          - -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
          - -/// tip - -Every time you install a new package with `pip` under that environment, activate the environment again. - -This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. - -/// +Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`. ### Install requirements using pip -After activating the environment as described above: +After activating the environment, install the required packages:
          @@ -160,7 +56,19 @@ $ bash scripts/format.sh It will also auto-sort all your imports. -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`. +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +
          + +```console +$ bash scripts/test-cov-html.sh +``` + +
          + +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. ## Docs @@ -482,17 +390,3 @@ Serving at: http://127.0.0.1:8008 * Search for such links in the translated document using the regex `#[^# ]`. * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -
          - -```console -$ bash scripts/test-cov-html.sh -``` - -
          - -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d70c5e48b..3324a7503 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -82,7 +82,9 @@ When referring to the remote machine, it's common to call it **server**, but als When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. -But you can also install an ASGI server manually: +But you can also install an ASGI server manually. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: //// tab | Uvicorn diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 433371b9d..efde5f3a1 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -39,6 +39,8 @@ And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of ## Install Gunicorn and Uvicorn +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: +
          ```console diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md new file mode 100644 index 000000000..78e82d5af --- /dev/null +++ b/docs/en/docs/environment-variables.md @@ -0,0 +1,300 @@ +# Environment Variables + +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip this. + +/// + +An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well). + +Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc. + +## Create and Use Env Vars + +You can **create** and use environment variables in the **shell (terminal)**, without needing Python: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +## Read env vars in Python + +You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +The second argument to `os.getenv()` is the default value to return. + +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// + +Then you could call that Python program: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
          + +//// + +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**. + +You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +
          + +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
          + +/// tip + +You can read more about it at The Twelve-Factor App: Config. + +/// + +## Types and Validation + +These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code. + +You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Environment Variable + +There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run. + +The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows. + +For example, the `PATH` environment variable could look like this: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +This means that the system should look for programs in the directories: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +This means that the system should look for programs in the directories: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable. + +For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list. + +If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**. + +### Installing Python and Updating the `PATH` + +When you install Python, you might be asked if you want to update the `PATH` environment variable. + +//// tab | Linux, macOS + +Let's say you install Python and it ends up in a directory `/opt/custompython/bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable. + +It could look like this: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +//// + +//// tab | Windows + +Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one. + +//// + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +So, if you type: + +
          + +```console +$ python +``` + +
          + +//// tab | Linux, macOS + +The system will **find** the `python` program in `/opt/custompython/bin` and run it. + +It would be roughly equivalent to typing: + +
          + +```console +$ /opt/custompython/bin/python +``` + +
          + +//// + +//// tab | Windows + +The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it. + +It would be roughly equivalent to typing: + +
          + +```console +$ C:\opt\custompython\bin\python +``` + +
          + +//// + +This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +With this you should have a basic understanding of what **environment variables** are and how to use them in Python. + +You can also read more about them in the Wikipedia for Environment Variable. + +In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them. + +For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md). diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index d76ef498b..ac4f4d00f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -128,6 +128,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a virtual environment and then install FastAPI: +
          ```console diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 5f8c51c4c..386fe5de9 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -4,9 +4,7 @@ This tutorial shows you how to use **FastAPI** with most of its features, step b Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs. -It is also built to work as a future reference. - -So you can come back and see exactly what you need. +It is also built to work as a future reference so you can come back and see exactly what you need. ## Run the code @@ -71,7 +69,9 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing ## Install FastAPI -The first step is to install FastAPI: +The first step is to install FastAPI. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then **install FastAPI**:
          diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 53d9eefde..9f19596a8 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -6,7 +6,11 @@ You can define files to be uploaded by the client using `File`. To receive uploaded files, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` This is because uploaded files are sent as "form data". diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 9b4342652..7830a2ba4 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -6,7 +6,11 @@ You can define files and form fields at the same time using `File` and `Form`. To receive uploaded files and/or form data, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 88b5b86b6..87cfdefbc 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -6,7 +6,11 @@ When you need to receive form fields instead of JSON, you can use `Form`. To use forms, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index c17e32f90..6a2093e6d 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -133,8 +133,17 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: To use `EmailStr`, first install `email-validator`. -E.g. `pip install email-validator` -or `pip install pydantic[email]`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install email-validator +``` + +or with: + +```console +$ pip install "pydantic[email]" +``` /// diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index ed427a282..4bd026caf 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -56,9 +56,13 @@ Prefer to use the `Annotated` version if possible. The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. -However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: +However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. -`pip install python-multipart` +To install it manually, make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it with: + +```console +$ pip install python-multipart +``` This is because **OAuth2** uses "form data" for sending the `username` and `password`. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 52877b916..ba2bfef29 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -28,7 +28,9 @@ If you want to play with JWT tokens and see how they work, check @@ -70,7 +72,7 @@ It supports many secure hashing algorithms and utilities to work with them. The recommended algorithm is "Bcrypt". -So, install PassLib with Bcrypt: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt:
          diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 0645cc9f1..56971bf9d 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -101,7 +101,9 @@ Now let's see what each file/module does. ## Install `SQLAlchemy` -First you need to install `SQLAlchemy`: +First you need to install `SQLAlchemy`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
          diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 95c8c5bef..06a87e92e 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -12,7 +12,11 @@ With it, you can use `httpx`. -E.g. `pip install httpx`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install httpx +``` /// @@ -206,7 +210,9 @@ If you have a Pydantic model in your test and you want to send its data to the a ## Run it -After that, you just need to install `pytest`: +After that, you just need to install `pytest`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
          diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md new file mode 100644 index 000000000..3c4aa49c1 --- /dev/null +++ b/docs/en/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Virtual Environments + +When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project. + +/// info + +If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓 + +/// + +/// tip + +A **virtual environment** is different than an **environment variable**. + +An **environment variable** is a variable in the system that can be used by programs. + +A **virtual environment** is a directory with some files in it. + +/// + +/// info + +This page will teach you how to use **virtual environments** and how they work. + +If you are ready to adopt a **tool that manages everything** for you (including installing Python), try uv. + +/// + +## Create a Project + +First, create a directory for your project. + +What I normally do is that I create a directory named `code` inside my home/user directory. + +And inside of that I create one directory per project. + +
          + +```console +// Go to the home directory +$ cd +// Create a directory for all your code projects +$ mkdir code +// Enter into that code directory +$ cd code +// Create a directory for this project +$ mkdir awesome-project +// Enter into that project directory +$ cd awesome-project +``` + +
          + +## Create a Virtual Environment + +When you start working on a Python project **for the first time**, create a virtual environment **inside your project**. + +/// tip + +You only need to do this **once per project**, not every time you work. + +/// + +//// tab | `venv` + +To create a virtual environment, you can use the `venv` module that comes with Python. + +
          + +```console +$ python -m venv .venv +``` + +
          + +/// details | What that command means + +* `python`: use the program called `python` +* `-m`: call a module as a script, we'll tell it which module next +* `venv`: use the module called `venv` that normally comes installed with Python +* `.venv`: create the virtual environment in the new directory `.venv` + +/// + +//// + +//// tab | `uv` + +If you have `uv` installed, you can use it to create a virtual environment. + +
          + +```console +$ uv venv +``` + +
          + +/// tip + +By default, `uv` will create a virtual environment in a directory called `.venv`. + +But you could customize it passing an additional argument with the directory name. + +/// + +//// + +That command creates a new virtual environment in a directory called `.venv`. + +/// details | `.venv` or other name + +You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`. + +/// + +## Activate the Virtual Environment + +Activate the new virtual environment so that any Python command you run or package you install uses it. + +/// tip + +Do this **every time** you start a **new terminal session** to work on the project. + +/// + +//// tab | Linux, macOS + +
          + +```console +$ source .venv/bin/activate +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
          + +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. Git Bash): + +
          + +```console +$ source .venv/Scripts/activate +``` + +
          + +//// + +/// tip + +Every time you install a **new package** in that environment, **activate** the environment again. + +This makes sure that if you use a **terminal (CLI) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need. + +/// + +## Check the Virtual Environment is Active + +Check that the virtual environment is active (the previous command worked). + +/// tip + +This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended. + +/// + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
          + +If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
          + +If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +## Upgrade `pip` + +/// tip + +If you use `uv` you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎 + +/// + +If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version. + +Many exotic errors while installing a package are solved by just upgrading `pip` first. + +/// tip + +You would normally do this **once**, right after you create the virtual environment. + +/// + +Make sure the virtual environment is active (with the command above) and then run: + +
          + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
          + +## Add `.gitignore` + +If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git. + +/// tip + +If you used `uv` to create the virtual environment, it already did this for you, you can skip this step. 😎 + +/// + +/// tip + +Do this **once**, right after you create the virtual environment. + +/// + +
          + +```console +$ echo "*" > .venv/.gitignore +``` + +
          + +/// details | What that command means + +* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit) +* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>` +* `.gitignore`: the name of the file where the text should be written + +And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory. + +That command will create a file `.gitignore` with the content: + +```gitignore +* +``` + +/// + +## Install Packages + +After activating the environment, you can install packages in it. + +/// tip + +Do this **once** when installing or upgrading the packages your project needs. + +If you need to upgrade a version or add a new package you would **do this again**. + +/// + +### Install Packages Directly + +If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly. + +/// tip + +It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`). + +/// + +//// tab | `pip` + +
          + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
          + +//// + +//// tab | `uv` + +If you have `uv`: + +
          + +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
          + +//// + +### Install from `requirements.txt` + +If you have a `requirements.txt`, you can now use it to install its packages. + +//// tab | `pip` + +
          + +```console +$ pip install -r requirements.txt +---> 100% +``` + +
          + +//// + +//// tab | `uv` + +If you have `uv`: + +
          + +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
          + +//// + +/// details | `requirements.txt` + +A `requirements.txt` with some packages could look like: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Run Your Program + +After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there. + +
          + +```console +$ python main.py + +Hello World +``` + +
          + +## Configure Your Editor + +You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors. + +For example: + +* VS Code +* PyCharm + +/// tip + +You normally have to do this only **once**, when you create the virtual environment. + +/// + +## Deactivate the Virtual Environment + +Once you are done working on your project you can **deactivate** the virtual environment. + +
          + +```console +$ deactivate +``` + +
          + +This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there. + +## Ready to Work + +Now you're ready to start working on your project. + + + +/// tip + +Do you want to understand what's all that above? + +Continue reading. 👇🤓 + +/// + +## Why Virtual Environments + +To work with FastAPI you need to install Python. + +After that, you would need to **install** FastAPI and any other **packages** you want to use. + +To install packages you would normally use the `pip` command that comes with Python (or similar alternatives). + +Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python). + +### The Problem + +So, what's the problem with installing packages in the global Python environment? + +At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱 + +For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install. + +If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with: + +
          + +```console +$ pip install "harry==1" +``` + +
          + +And then you would end up with `harry` version `1` installed in your global Python environment. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`). + +
          + +```console +$ pip install "harry==3" +``` + +
          + +And then you would end up with `harry` version `3` installed in your global Python environment. + +And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip + +It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly. + +/// + +Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working. + +Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system. + +## Where are Packages Installed + +When you install Python, it creates some directories with some files in your computer. + +Some of these directories are the ones in charge of having all the packages you install. + +When you run: + +
          + +```console +// Don't run this now, it's just an example 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
          + +That will download a compressed file with the FastAPI code, normally from PyPI. + +It will also **download** files for other packages that FastAPI depends on. + +Then it will **extract** all those files and put them in a directory in your computer. + +By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**. + +## What are Virtual Environments + +The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on. + +A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. + +This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## What Does Activating a Virtual Environment Mean + +When you activate a virtual environment, for example with: + +//// tab | Linux, macOS + +
          + +```console +$ source .venv/bin/activate +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
          + +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. Git Bash): + +
          + +```console +$ source .venv/Scripts/activate +``` + +
          + +//// + +That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands. + +One of those variables is the `PATH` variable. + +/// tip + +You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section. + +/// + +Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable. + +Let's say that before activating the environment, the `PATH` variable looked like this: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +That means that the system would look for programs in: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +That means that the system would look for programs in: + +* `C:\Windows\System32` + +//// + +After activating the virtual environment, the `PATH` variable would look something like this: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +That means that the system will now start looking first look for programs in: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +and use that one. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +That means that the system will now start looking first look for programs in: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +and use that one. + +//// + +An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment). + +Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does. + +## Checking a Virtual Environment + +When you check if a virtual environment is active, for example with: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
          + +//// + +That means that the `python` program that will be used is the one **in the virtual environment**. + +you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell. + +The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program. + +The most important part is that when you call `python`, that is the exact "`python`" that will be executed. + +So, you can confirm if you are in the correct virtual environment. + +/// tip + +It's easy to activate one virtual environment, get one Python, and then **go to another project**. + +And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project. + +It's useful being able to check what `python` is being used. 🤓 + +/// + +## Why Deactivate a Virtual Environment + +For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment. + +And then you want to work on **another project** `prisoner-of-azkaban`. + +You go to that project: + +
          + +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
          + +If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`. + +
          + +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
          + +But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`. + +
          + +```console +$ cd ~/code/prisoner-of-azkaban + +// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎 +$ deactivate + +// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Now when you run python, it will find the package sirius installed in this virtual environment ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
          + +## Alternatives + +This is a simple guide to get you started and teach you how everything works **underneath**. + +There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects. + +Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try uv. + +`uv` can do a lot of things, it can: + +* **Install Python** for you, including different versions +* Manage the **virtual environment** for your projects +* Install **packages** +* Manage package **dependencies and versions** for your project +* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking** +* And many other things + +## Conclusion + +If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓 + +Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎 diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d0527ca3c..6f1e12511 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -108,6 +108,8 @@ nav: - learn/index.md - python-types.md - async.md + - environment-variables.md + - virtual-environments.md - Tutorial - User Guide: - tutorial/index.md - tutorial/first-steps.md From d0ce9d2bdf7f3c78b6f193288b9925b952da27c9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 22 Aug 2024 00:47:57 +0000 Subject: [PATCH 135/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 12f1f50cd..a8bbcc3b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). From 8f037167571ca60f87677594418fc68a05db6a9f Mon Sep 17 00:00:00 2001 From: Aymen Date: Sat, 24 Aug 2024 04:16:23 +0100 Subject: [PATCH 136/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20a=20typo=20in=20vi?= =?UTF-8?q?rtual=20environement=20page=20(#12064)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/virtual-environments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index 3c4aa49c1..fcc72fbe7 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -558,7 +558,7 @@ The solution to the problems of having all the packages in the global environmen A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. -This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. +This way, each project will have its own virtual environment (`.venv` directory) with its own packages. ```mermaid flowchart TB From 6935fe8d38fe4befd0cc1cd8ddbbd836bb809497 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 03:16:48 +0000 Subject: [PATCH 137/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a8bbcc3b7..8059de05d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). From 22bf988dfb085f45449bc137401af0105a86cdf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 23 Aug 2024 22:48:20 -0500 Subject: [PATCH 138/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8059de05d..c872f59e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,7 +14,7 @@ hide: ### Docs -* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). +* 📝 Fix a typo in `docs/en/docs/virtual-environments.md`. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). @@ -36,7 +36,7 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). -* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 3a4ac2467594d0ccad92ecfb7f7f10ffa5d1d992 Mon Sep 17 00:00:00 2001 From: Pastukhov Nikita Date: Sat, 24 Aug 2024 22:09:52 +0300 Subject: [PATCH 139/356] =?UTF-8?q?=F0=9F=90=9B=20Ensure=20that=20`app.inc?= =?UTF-8?q?lude=5Frouter`=20merges=20nested=20lifespans=20(#9630)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Marcelo Trylesinski Co-authored-by: Sebastián Ramírez --- fastapi/routing.py | 27 +++++++- tests/test_router_events.py | 135 +++++++++++++++++++++++++++++++++++- 2 files changed, 158 insertions(+), 4 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 2e7959f3d..49f1b6013 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -3,14 +3,16 @@ import dataclasses import email.message import inspect import json -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, + AsyncIterator, Callable, Coroutine, Dict, List, + Mapping, Optional, Sequence, Set, @@ -67,7 +69,7 @@ from starlette.routing import ( websocket_session, ) from starlette.routing import Mount as Mount # noqa -from starlette.types import ASGIApp, Lifespan, Scope +from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated @@ -119,6 +121,23 @@ def _prepare_response_content( return res +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + async def serialize_response( *, field: Optional[ModelField] = None, @@ -1308,6 +1327,10 @@ class APIRouter(routing.Router): self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) def get( self, diff --git a/tests/test_router_events.py b/tests/test_router_events.py index 1b9de18ae..dd7ff3314 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -1,8 +1,8 @@ from contextlib import asynccontextmanager -from typing import AsyncGenerator, Dict +from typing import AsyncGenerator, Dict, Union import pytest -from fastapi import APIRouter, FastAPI +from fastapi import APIRouter, FastAPI, Request from fastapi.testclient import TestClient from pydantic import BaseModel @@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None: assert response.json() == {"message": "Hello World"} assert state.app_startup is True assert state.app_shutdown is True + + +def test_router_nested_lifespan_state(state: State) -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.app_startup = True + yield {"app": True} + state.app_shutdown = True + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.router_startup = True + yield {"router": True} + state.router_shutdown = True + + @asynccontextmanager + async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.sub_router_startup = True + yield {"sub_router": True} + state.sub_router_shutdown = True + + sub_router = APIRouter(lifespan=subrouter_lifespan) + + router = APIRouter(lifespan=router_lifespan) + router.include_router(sub_router) + + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + @app.get("/") + def main(request: Request) -> Dict[str, str]: + assert request.state.app + assert request.state.router + assert request.state.sub_router + return {"message": "Hello World"} + + assert state.app_startup is False + assert state.router_startup is False + assert state.sub_router_startup is False + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + + with TestClient(app) as client: + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"message": "Hello World"} + + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is True + assert state.router_shutdown is True + assert state.sub_router_shutdown is True + + +def test_router_nested_lifespan_state_overriding_by_parent() -> None: + @asynccontextmanager + async def lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "app_specific": True, + "overridden": "app", + } + + @asynccontextmanager + async def router_lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "router_specific": True, + "overridden": "router", # should override parent + } + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == { + "app_specific": True, + "router_specific": True, + "overridden": "app", + } + + +def test_merged_no_return_lifespans_return_none() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert not client.app_state + + +def test_merged_mixed_state_lifespans() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + yield {"router": True} + + @asynccontextmanager + async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + sub_router = APIRouter(lifespan=sub_router_lifespan) + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + router.include_router(sub_router) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == {"router": True} From 48b36f26d83d607a044866633068dbf46e723e0f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 19:10:14 +0000 Subject: [PATCH 140/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c872f59e9..d9cefc989 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). + ### Refactors * 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie). From 51b625e127982f626886d467122ef85d5772d1db Mon Sep 17 00:00:00 2001 From: Giunio <59511892+giunio-prc@users.noreply.github.com> Date: Sat, 24 Aug 2024 21:27:37 +0200 Subject: [PATCH 141/356] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`allow=5Finf=5Fnan?= =?UTF-8?q?`=20option=20for=20Param=20and=20Body=20classes=20(#11867)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg --- fastapi/params.py | 4 +- tests/test_allow_inf_nan_in_enforcing.py | 83 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 tests/test_allow_inf_nan_in_enforcing.py diff --git a/fastapi/params.py b/fastapi/params.py index 860146531..cc2a5c13c 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -91,7 +91,7 @@ class Param(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -547,7 +547,7 @@ class Body(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py new file mode 100644 index 000000000..9e855fdf8 --- /dev/null +++ b/tests/test_allow_inf_nan_in_enforcing.py @@ -0,0 +1,83 @@ +import pytest +from fastapi import Body, FastAPI, Query +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/") +async def get( + x: Annotated[float, Query(allow_inf_nan=True)] = 0, + y: Annotated[float, Query(allow_inf_nan=False)] = 0, + z: Annotated[float, Query()] = 0, + b: Annotated[float, Body(allow_inf_nan=False)] = 0, +) -> str: + return "OK" + + +client = TestClient(app) + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_true(value: str, code: int): + response = client.post(f"/?x={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_false(value: str, code: int): + response = client.post(f"/?y={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_default(value: str, code: int): + response = client.post(f"/?z={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_body(value: str, code: int): + response = client.post("/", json=value) + assert response.status_code == code, response.text From b69a9f3b6f822e71be275ca20347a0ab3dfe99e8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 19:27:59 +0000 Subject: [PATCH 142/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d9cefc989..28d430ab0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Fixes +* 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). * 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). ### Refactors From d00af00d3f15e9a963e2f1baf8f9b4c8357f6f66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 14:34:50 -0500 Subject: [PATCH 143/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 28d430ab0..2af28ae05 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.2 + ### Fixes * 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 0b79d45ef..ac2508d89 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.1" +__version__ = "0.112.2" from starlette import status as status From 9656895b60e85aeee82a599dc601813ba815b0df Mon Sep 17 00:00:00 2001 From: GPla <36087062+GPla@users.noreply.github.com> Date: Sat, 24 Aug 2024 22:04:30 +0200 Subject: [PATCH 144/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20in=20Docker?= =?UTF-8?q?=20docs=20about=20ensuring=20graceful=20shutdowns=20and=20lifes?= =?UTF-8?q?pan=20events=20with=20`CMD`=20exec=20form=20(#11960)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- docs/en/docs/deployment/docker.md | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 253e25fe5..ab1c2201f 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -232,6 +232,38 @@ Review what each line does by clicking each number bubble in the code. 👆 /// +/// warning + +Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below. + +/// + +#### Use `CMD` - Exec Form + +The `CMD` Docker instruction can be written using two forms: + +✅ **Exec** form: + +```Dockerfile +# ✅ Do this +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Shell** form: + +```Dockerfile +# ⛔️ Don't do this +CMD fastapi run app/main.py --port 80 +``` + +Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered. + +You can read more about it in the Docker docs for shell and exec form. + +This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: Why do my services take 10 seconds to recreate or stop?. + +#### Directory Structure + You should now have a directory structure like: ``` From e4727ed20aa83604a9d28d397e4ce4994f8b9640 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 20:04:51 +0000 Subject: [PATCH 145/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2af28ae05..83d992b8b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). + ## 0.112.2 ### Fixes From 6aa44a85a211f5175b2b45d0dbf23128f6be0627 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Sat, 24 Aug 2024 23:52:09 +0200 Subject: [PATCH 146/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typos=20an?= =?UTF-8?q?d=20issues=20in=20the=20documentation=20(#12063)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/async.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 ++-- docs/en/docs/tutorial/body-multiple-params.md | 2 +- docs/en/docs/tutorial/body-updates.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/cors.md | 2 +- .../docs/tutorial/dependencies/classes-as-dependencies.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/handling-errors.md | 4 ++-- docs/en/docs/tutorial/index.md | 2 +- docs/en/docs/tutorial/middleware.md | 2 +- docs/en/docs/tutorial/query-params-str-validations.md | 6 +++--- docs/en/docs/tutorial/schema-extra-example.md | 2 +- docs/en/docs/tutorial/security/first-steps.md | 2 +- docs/en/docs/tutorial/security/get-current-user.md | 2 +- 19 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 889a89ed7..ec7a95497 100644 --- a/README.md +++ b/README.md @@ -394,7 +394,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 73071ed1b..2251659c5 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -28,7 +28,7 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it. +Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 7cf4af627..752a5c247 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -292,7 +292,7 @@ For example: ### Concurrency + Parallelism: Web + Machine Learning -With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). +With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index ac4f4d00f..3ed3d7bf6 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -390,7 +390,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 4ed1fc680..6994adb5f 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -324,7 +324,7 @@ In Python 3.6 and above (including Python 3.10) you can declare it by importing {!../../../docs_src/python_types/tutorial009.py!} ``` -Using `Optional[str]` instead of just `str` will let the editor help you detecting errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. +Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. `Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 97f6b205b..230f9c08c 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -1,6 +1,6 @@ # Bigger Applications - Multiple Files -If you are building an application or a web API, it's rarely the case that you can put everything on a single file. +If you are building an application or a web API, it's rarely the case that you can put everything in a single file. **FastAPI** provides a convenience tool to structure your application while keeping all the flexibility. @@ -478,7 +478,7 @@ We can declare all that without having to modify the original `APIRouter` by pas {!../../../docs_src/bigger_applications/app/main.py!} ``` -That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. +That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. The result is that in our app, each of the *path operations* from the `admin` module will have: diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 511fb358e..d63cd2529 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -97,7 +97,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// -In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models). +In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models). So, it will then use the parameter names as keys (field names) in the body, and expect a body like: diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 261f44d33..3257f9a08 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -155,7 +155,7 @@ In summary, to apply partial updates you would: * Put that data in a Pydantic model. * Generate a `dict` without default values from the input model (using `exclude_unset`). * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. -* Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). +* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 608b50dbb..83f08ce84 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -123,7 +123,7 @@ The JSON Schemas of your models will be part of your OpenAPI generated schema, a -And will be also used in the API docs inside each *path operation* that needs them: +And will also be used in the API docs inside each *path operation* that needs them: diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index fd329e138..7dd0a5df5 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -40,7 +40,7 @@ You can configure it in your **FastAPI** application using the `CORSMiddleware`. * Create a list of allowed origins (as strings). * Add it as a "middleware" to your **FastAPI** application. -You can also specify if your backend allows: +You can also specify whether your backend allows: * Credentials (Authorization headers, Cookies, etc). * Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`. diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index a392672bb..b3394f14e 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -381,7 +381,7 @@ The last `CommonQueryParams`, in: ...is what **FastAPI** will actually use to know what is the dependency. -From it is that FastAPI will extract the declared parameters and that is what FastAPI will actually call. +It is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call. --- diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 849dee41f..3009acaf3 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -49,7 +49,7 @@ Here are some of the additional data types you can use: * `Decimal`: * Standard Python `Decimal`. * In requests and responses, handled the same as a `float`. -* You can check all the valid pydantic data types here: Pydantic data types. +* You can check all the valid Pydantic data types here: Pydantic data types. ## Example diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index ca3cff661..14a3cf998 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -176,7 +176,7 @@ These are technical details that you might skip if it's not important for you no **FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log. -But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`. +But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`. It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code. @@ -262,7 +262,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException ### Reuse **FastAPI**'s exception handlers -If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`: +If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" {!../../../docs_src/handling_errors/tutorial006.py!} diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 386fe5de9..bf613aace 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -95,7 +95,7 @@ If you don't want to have those optional dependencies, you can instead install ` There is also an **Advanced User Guide** that you can read later after this **Tutorial - User guide**. -The **Advanced User Guide**, builds on this, uses the same concepts, and teaches you some extra features. +The **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features. But you should first read the **Tutorial - User Guide** (what you are reading right now). diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index f0b3faf3b..06fb3f504 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -29,7 +29,7 @@ The middleware function receives: * A function `call_next` that will receive the `request` as a parameter. * This function will pass the `request` to the corresponding *path operation*. * Then it returns the `response` generated by the corresponding *path operation*. -* You can then modify further the `response` before returning it. +* You can then further modify the `response` before returning it. ```Python hl_lines="8-9 11 14" {!../../../docs_src/middleware/tutorial001.py!} diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 859242d93..dd101a2a6 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -273,7 +273,7 @@ The **default** value of the **function parameter** is the **actual default** va You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter. -When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. +When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other places**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like Typer. 🚀 @@ -645,7 +645,7 @@ Remember that in most of the cases, when something is required, you can simply o ## Query parameter list / multiple values -When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values. +When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values. For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: @@ -1182,4 +1182,4 @@ Validations specific for strings: In these examples you saw how to declare validations for `str` values. -See the next chapters to see how to declare validations for other types, like numbers. +See the next chapters to learn how to declare validations for other types, like numbers. diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 70745b048..20dee3a4f 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -347,7 +347,7 @@ If the ideas above already work for you, that might be enough, and you probably Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. -JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version. +JSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version. OpenAPI also added `example` and `examples` fields to other parts of the specification: diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 4bd026caf..d1fe0163e 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -152,7 +152,7 @@ A "bearer" token is not the only option. But it's the best one for our use case. -And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. +And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs. In that case, **FastAPI** also provides you with the tools to build it. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 6f3bf3944..7faaa3e13 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -316,7 +316,7 @@ And you can make it as complex as you want. And still, have it written only once But you can have thousands of endpoints (*path operations*) using the same security system. -And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create. +And all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create. And all these thousands of *path operations* can be as small as 3 lines: From d8e526c1db42b9049a3c9a26f2ac91109c896812 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 21:52:29 +0000 Subject: [PATCH 147/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83d992b8b..2218b352b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). ## 0.112.2 From c692176d4288e8b8f6f404c7c15aaab74083a6e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 19:01:04 -0500 Subject: [PATCH 148/356] =?UTF-8?q?=F0=9F=93=9D=20Clarify=20`response=5Fcl?= =?UTF-8?q?ass`=20parameter,=20validations,=20and=20returning=20a=20respon?= =?UTF-8?q?se=20directly=20(#12067)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/custom-response.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 8a6555dba..79f755815 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -4,9 +4,9 @@ By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. -But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). +But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). -But you can also declare the `Response` that you want to be used, in the *path operation decorator*. +But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter. The contents that you return from your *path operation function* will be put inside of that `Response`. From b5cbff9521c6c800aebf37d73a3532951db95bff Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 25 Aug 2024 00:01:26 +0000 Subject: [PATCH 149/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2218b352b..ac8f16f53 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From bd1b77548f0f1788c5ae0fbd8144f5139bdb959e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 21:44:06 -0500 Subject: [PATCH 150/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20about=20?= =?UTF-8?q?serving=20FastAPI:=20ASGI=20servers,=20Docker=20containers,=20e?= =?UTF-8?q?tc.=20(#12069)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/sub-applications.md | 4 +- docs/en/docs/alternatives.md | 2 +- docs/en/docs/contributing.md | 2 +- docs/en/docs/deployment/concepts.md | 8 +- docs/en/docs/deployment/docker.md | 226 ++++--------------- docs/en/docs/deployment/manually.md | 89 +------- docs/en/docs/deployment/server-workers.md | 165 ++++++-------- docs/en/docs/deployment/versions.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 +- 9 files changed, 129 insertions(+), 373 deletions(-) diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index 8c52e091f..568a9deca 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -36,12 +36,12 @@ In this case, it will be mounted at the path `/subapi`: ### Check the automatic API docs -Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: +Now, run the `fastapi` command with your file:
          ```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 2ad584c95..e98c0475a 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -474,7 +474,7 @@ It is the recommended server for Starlette and **FastAPI**. The main web server to run **FastAPI** applications. -You can combine it with Gunicorn, to have an asynchronous multi-process server. +You can also use the `--workers` command line option to have an asynchronous multi-process server. Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 91d5724a8..0dc07b89b 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -170,7 +170,7 @@ If you run the examples with, e.g.:
          ```console -$ uvicorn tutorial001:app --reload +$ fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index f917d18b3..69ee71a73 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally. And it will work and will be useful **during development**. @@ -178,7 +178,7 @@ For example, this could be handled by: ## Replication - Processes and Memory -With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently. +With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently. But in many cases, you will want to run several worker processes at the same time. @@ -232,9 +232,7 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: -* **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**. -* **Uvicorn** managing **Uvicorn workers** +* **Uvicorn** with `--workers` * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index ab1c2201f..2d832a238 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -167,22 +167,22 @@ def read_item(item_id: int, q: Union[str, None] = None): Now in the same project directory create a file `Dockerfile` with: ```{ .dockerfile .annotate } -# (1) +# (1)! FROM python:3.9 -# (2) +# (2)! WORKDIR /code -# (3) +# (3)! COPY ./requirements.txt /code/requirements.txt -# (4) +# (4)! RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (5) +# (5)! COPY ./app /code/app -# (6) +# (6)! CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` @@ -400,10 +400,10 @@ COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (1) +# (1)! COPY ./main.py /code/ -# (2) +# (2)! CMD ["fastapi", "run", "main.py", "--port", "80"] ``` @@ -456,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c ## Replication - Number of Processes -If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container. +If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**. -In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers. +In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers. ### Load Balancer @@ -490,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level. -So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers). +So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers). -Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. +Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. ### Containers with Multiple Processes and Special Cases -Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside. +Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside. -In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +In those cases, you can use the `--workers` command line option to set the number of workers that you want to run: -Here are some examples of when that could make sense: +```{ .dockerfile .annotate } +FROM python:3.9 -#### A Simple App +WORKDIR /code -You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster. +COPY ./requirements.txt /code/requirements.txt -#### Docker Compose +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. +COPY ./app /code/app -Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` -#### Prometheus and Other Reasons +1. Here we use the `--workers` command line option to set the number of workers to 4. -You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them. +Here are some examples of when that could make sense: -For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come. +#### A Simple App + +You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster. + +#### Docker Compose -In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers. +You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. -Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container. +Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. --- @@ -541,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster). -If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. +If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. ## Previous Steps Before Starting and Containers @@ -561,80 +568,26 @@ If in your use case there's no problem in running those previous steps **multipl ### Single Container -If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally. +If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. -## Official Docker Image with Gunicorn - Uvicorn +### Base Docker Image -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}. +There used to be an official FastAPI Docker image: tiangolo/uvicorn-gunicorn-fastapi. But it is now deprecated. ⛔️ -This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). - -* tiangolo/uvicorn-gunicorn-fastapi. - -/// warning - -There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -/// +You should probably **not** use this base Docker image (or any other similar one). -This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. +If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). -It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files. +And if you need to have multiple workers, you can simply use the `--workers` command line option. -It also supports running **previous steps before starting** with a script. +/// note | Technical Details -/// tip +The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes. -To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. +But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅). /// -### Number of Processes on the Official Docker Image - -The **number of processes** on this image is **computed automatically** from the CPU **cores** available. - -This means that it will try to **squeeze** as much **performance** from the CPU as possible. - -You can also adjust it with the configurations using **environment variables**, etc. - -But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that. - -So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨 - -### Create a `Dockerfile` - -Here's how you would create a `Dockerfile` based on this image: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app -``` - -### Bigger Applications - -If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like: - -```Dockerfile hl_lines="7" -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app/app -``` - -### When to Use - -You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc. - ## Deploy the Container Image After having a Container (Docker) Image there are several ways to deploy it. @@ -647,98 +600,9 @@ For example: * With another tool like Nomad * With a cloud service that takes your container image and deploys it -## Docker Image with Poetry +## Docker Image with `uv` -If you use Poetry to manage your project's dependencies, you could use Docker multi-stage building: - -```{ .dockerfile .annotate } -# (1) -FROM python:3.9 as requirements-stage - -# (2) -WORKDIR /tmp - -# (3) -RUN pip install poetry - -# (4) -COPY ./pyproject.toml ./poetry.lock* /tmp/ - -# (5) -RUN poetry export -f requirements.txt --output requirements.txt --without-hashes - -# (6) -FROM python:3.9 - -# (7) -WORKDIR /code - -# (8) -COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt - -# (9) -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# (10) -COPY ./app /code/app - -# (11) -CMD ["fastapi", "run", "app/main.py", "--port", "80"] -``` - -1. This is the first stage, it is named `requirements-stage`. - -2. Set `/tmp` as the current working directory. - - Here's where we will generate the file `requirements.txt` - -3. Install Poetry in this Docker stage. - -4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory. - - Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet. - -5. Generate the `requirements.txt` file. - -6. This is the final stage, anything here will be preserved in the final container image. - -7. Set the current working directory to `/code`. - -8. Copy the `requirements.txt` file to the `/code` directory. - - This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it. - -9. Install the package dependencies in the generated `requirements.txt` file. - -10. Copy the `app` directory to the `/code` directory. - -11. Use the `fastapi run` command to run your app. - -/// tip - -Click the bubble numbers to see what each line does. - -/// - -A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. - -The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file. - -This `requirements.txt` file will be used with `pip` later in the **next stage**. - -In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded. - -When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies. - -Then in the next (and final) stage you would build the image more or less in the same way as described before. - -### Behind a TLS Termination Proxy - Poetry - -Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: - -```Dockerfile -CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] -``` +If you are using uv to install and manage your project, you can follow their uv Docker guide. ## Recap @@ -754,5 +618,3 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 - -In certain special cases, you might want to use the official Docker image for FastAPI. 🤓 diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 3324a7503..3f7c7a008 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -67,6 +67,8 @@ There are several alternatives, including: * Uvicorn: a high performance ASGI server. * Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. * Daphne: the ASGI server built for Django Channels. +* Granian: A Rust HTTP server for Python applications. +* NGINX Unit: NGINX Unit is a lightweight and versatile web application runtime. ## Server Machine and Server Program @@ -84,11 +86,9 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca But you can also install an ASGI server manually. -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application. -//// tab | Uvicorn - -* Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. +For example, to install Uvicorn:
          @@ -100,6 +100,8 @@ $ pip install "uvicorn[standard]"
          +A similar process would apply to any other ASGI server program. + /// tip By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. @@ -110,32 +112,10 @@ When you install FastAPI with something like `pip install "fastapi[standard]"` y /// -//// - -//// tab | Hypercorn - -* Hypercorn, an ASGI server also compatible with HTTP/2. - -
          - -```console -$ pip install hypercorn - ----> 100% -``` - -
          - -...or any other ASGI server. - -//// - ## Run the Server Program If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: -//// tab | Uvicorn -
          ```console @@ -146,22 +126,6 @@ $ uvicorn main:app --host 0.0.0.0 --port 80
          -//// - -//// tab | Hypercorn - -
          - -```console -$ hypercorn main:app --bind 0.0.0.0:80 - -Running on 0.0.0.0:8080 over http (CTRL + C to quit) -``` - -
          - -//// - /// note The command `uvicorn main:app` refers to: @@ -177,9 +141,11 @@ from main import app /// +Each alternative ASGI server program would have a similar command, you can read more in their respective documentation. + /// warning -Uvicorn and others support a `--reload` option that is useful during development. +Uvicorn and other servers support a `--reload` option that is useful during development. The `--reload` option consumes much more resources, is more unstable, etc. @@ -187,43 +153,6 @@ It helps a lot during **development**, but you **shouldn't** use it in **product /// -## Hypercorn with Trio - -Starlette and **FastAPI** are based on AnyIO, which makes them compatible with both Python's standard library asyncio and Trio. - -Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses `uvloop`, the high-performance drop-in replacement for `asyncio`. - -But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨ - -### Install Hypercorn with Trio - -First you need to install Hypercorn with Trio support: - -
          - -```console -$ pip install "hypercorn[trio]" ----> 100% -``` - -
          - -### Run with Trio - -Then you can pass the command line option `--worker-class` with the value `trio`: - -
          - -```console -$ hypercorn main:app --worker-class trio -``` - -
          - -And that will start Hypercorn with your app using Trio as the backend. - -Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉 - ## Deployment Concepts These examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`). diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index efde5f3a1..5e369e071 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# Server Workers - Uvicorn with Workers Let's check back those deployment concepts from before: @@ -9,125 +9,92 @@ Let's check back those deployment concepts from before: * Memory * Previous steps before starting -Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**. +Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**. When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. -Here I'll show you how to use **Gunicorn** with **Uvicorn worker processes**. +Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly. /// info If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. -In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. /// -## Gunicorn with Uvicorn Workers +## Multiple Workers -**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **ASGI standard**. +You can start multiple workers with the `--workers` command line option: -But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class. +//// tab | `fastapi` -And **Uvicorn** has a **Gunicorn-compatible worker class**. - -Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**. - -And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. - -## Install Gunicorn and Uvicorn - -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: +If you use the `fastapi` command:
          ```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% +$
           fastapi run --workers 4 main.py
          +INFO     Using path main.py
          +INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
          +INFO     Searching for package file structure from directories with __init__.py files
          +INFO     Importing from /home/user/code/awesomeapp
          +
          + ╭─ Python module file ─╮
          + │                      │
          + │  🐍 main.py          │
          + │                      │
          + ╰──────────────────────╯
          +
          +INFO     Importing module main
          +INFO     Found importable FastAPI app
          +
          + ╭─ Importable FastAPI app ─╮
          + │                          │
          + │  from main import app    │
          + │                          │
          + ╰──────────────────────────╯
          +
          +INFO     Using import string main:app
          +
          + ╭─────────── FastAPI CLI - Production mode ───────────╮
          + │                                                     │
          + │  Serving at: http://0.0.0.0:8000                    │
          + │                                                     │
          + │  API docs: http://0.0.0.0:8000/docs                 │
          + │                                                     │
          + │  Running in production mode, for development use:   │
          + │                                                     │
          + fastapi dev
          + │                                                     │
          + ╰─────────────────────────────────────────────────────╯
          +
          +INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
          +INFO:     Started parent process [27365]
          +INFO:     Started server process [27368]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27369]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27370]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27367]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +
          ```
          -That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn. +//// -## Run Gunicorn with Uvicorn Workers +//// tab | `uvicorn` -Then you can run Gunicorn with: - -
          - -```console -$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 - -[19499] [INFO] Starting gunicorn 20.1.0 -[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) -[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker -[19511] [INFO] Booting worker with pid: 19511 -[19513] [INFO] Booting worker with pid: 19513 -[19514] [INFO] Booting worker with pid: 19514 -[19515] [INFO] Booting worker with pid: 19515 -[19511] [INFO] Started server process [19511] -[19511] [INFO] Waiting for application startup. -[19511] [INFO] Application startup complete. -[19513] [INFO] Started server process [19513] -[19513] [INFO] Waiting for application startup. -[19513] [INFO] Application startup complete. -[19514] [INFO] Started server process [19514] -[19514] [INFO] Waiting for application startup. -[19514] [INFO] Application startup complete. -[19515] [INFO] Started server process [19515] -[19515] [INFO] Waiting for application startup. -[19515] [INFO] Application startup complete. -``` - -
          - -Let's see what each of those options mean: - -* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application. - * You can imagine that `main:app` is equivalent to a Python `import` statement like: - - ```Python - from main import app - ``` - - * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. - -* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. - -* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. - * Here we pass the class that Gunicorn can import and use with: - - ```Python - import uvicorn.workers.UvicornWorker - ``` - -* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port. - * If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`. - -In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number). - -You can see that: - -* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number). -* Then it starts `Listening at: http://0.0.0.0:80`. -* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`. -* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`. - -Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above. - -Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc. - -## Uvicorn with Workers - -Uvicorn also has an option to start and run several **worker processes**. - -Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager. - -In any case, you would run it like this: +If you prefer to use the `uvicorn` command directly:
          @@ -151,13 +118,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
          +//// + The only new option here is `--workers` telling Uvicorn to start 4 worker processes. You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`. ## Deployment Concepts -Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. +Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others: @@ -172,13 +141,11 @@ From the list of deployment concepts from above, using workers would mainly help In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. -I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. - -There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. +I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. ## Recap -You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. +You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself. diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index e387d5712..23f49cf99 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -30,7 +30,7 @@ fastapi[standard]>=0.112.0,<0.113.0 that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. -If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. +If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. ## Available versions diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 230f9c08c..1c33fd051 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -519,12 +519,12 @@ As we cannot just isolate them and "mount" them independently of the rest, the * ## Check the automatic API docs -Now, run `uvicorn`, using the module `app.main` and the variable `app`: +Now, run your app:
          ```console -$ uvicorn app.main:app --reload +$ fastapi dev app/main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` From 3a96938771c67a9cc343a38b143f55b618817bd3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 25 Aug 2024 02:44:27 +0000 Subject: [PATCH 151/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ac8f16f53..b5b3188ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From 5fdbeed7928231a249d479c0c266f83877cafce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 25 Aug 2024 21:14:56 -0500 Subject: [PATCH 152/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20`latest-changes?= =?UTF-8?q?`=20GitHub=20Action=20(#12073)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/latest-changes.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 27e062d09..16da3bc63 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,8 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.3.0 - # - uses: tiangolo/latest-changes@main + - uses: tiangolo/latest-changes@0.3.1 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md From 9416e89bd7e3491157f8c962012aebd7be7ed5d6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 26 Aug 2024 02:15:38 +0000 Subject: [PATCH 153/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b5b3188ef..1dff0bddc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Internal + +* 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.2 ### Fixes From f41f6234af886914ebd3022faad80bb6320bb1bf Mon Sep 17 00:00:00 2001 From: lkw123 <2020393267@qq.com> Date: Wed, 28 Aug 2024 21:48:13 +0800 Subject: [PATCH 154/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/how-to/index.md`=20(#12070)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/how-to/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md index 262dcfaee..ac097618b 100644 --- a/docs/zh/docs/how-to/index.md +++ b/docs/zh/docs/how-to/index.md @@ -6,7 +6,7 @@ 如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 -/// 小技巧 +/// tip | 小技巧 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 From be9abcf35315cff34d30e86ce7d2deec3e3df9be Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 13:48:40 +0000 Subject: [PATCH 155/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1dff0bddc..20caacd64 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Translations + +* 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). + ### Internal * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 4909e44a7ff9b7048f7e6db8c7ad72283fd6a30d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 28 Aug 2024 09:07:00 -0500 Subject: [PATCH 156/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12076)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.1 → v0.6.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.1...v0.6.2) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7532f21b5..317514062 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.1 + rev: v0.6.2 hooks: - id: ruff args: From 48bf0db58fb5008c78d758d830e0d58f34edfb62 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 14:07:23 +0000 Subject: [PATCH 157/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 20caacd64..baf25d451 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). ## 0.112.2 From cabed9efb6a6b615f3bf45e9e523ff290f252f0f Mon Sep 17 00:00:00 2001 From: Alec Gillis Date: Wed, 28 Aug 2024 16:33:37 -0700 Subject: [PATCH 158/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20comma=20in=20`d?= =?UTF-8?q?ocs/en/docs/async.md`=20(#12062)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alec Gillis Co-authored-by: Sofie Van Landeghem --- docs/en/docs/async.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 752a5c247..63bd8ca68 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -387,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". From a930128910f65e53bdff76f4e52f484e5129f60b Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:35:03 +0000 Subject: [PATCH 159/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index baf25d451..838516421 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). From 9b35d355bfb44c33000359a2b24f215286996693 Mon Sep 17 00:00:00 2001 From: Muhammad Ashiq Ameer <46787072+MuhammadAshiqAmeer@users.noreply.github.com> Date: Thu, 29 Aug 2024 05:09:15 +0530 Subject: [PATCH 160/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs=5Fsrc/pat?= =?UTF-8?q?h=5Fparams=5Fnumeric=5Fvalidations/tutorial006.py`=20(#11478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- docs_src/path_params_numeric_validations/tutorial006.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an_py39.py | 2 ++ 3 files changed, 6 insertions(+) diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0ea32694a..f07629aa0 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -13,4 +13,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py index 22a143623..ac4732573 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an.py @@ -14,4 +14,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py index 804751893..426ec3776 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py @@ -15,4 +15,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results From 33328952518b78ed40d5f58cf21f3e40e48f6615 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:40:13 +0000 Subject: [PATCH 161/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 838516421..34a3fbc57 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). From ae27540348d943e786e83176a8fc32d535baece7 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Thu, 29 Aug 2024 01:41:46 +0200 Subject: [PATCH 162/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Dutch=20translatio?= =?UTF-8?q?n=20for=20`docs/nl/docs/index.md`=20(#12042)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Max Scheijen --- docs/en/mkdocs.yml | 2 + docs/nl/docs/index.md | 494 ++++++++++++++++++++++++++++++++++++++++++ docs/nl/mkdocs.yml | 1 + 3 files changed, 497 insertions(+) create mode 100644 docs/nl/docs/index.md create mode 100644 docs/nl/mkdocs.yml diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 6f1e12511..528c80b8e 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -363,6 +363,8 @@ extra: name: ja - 日本語 - link: /ko/ name: ko - 한국어 + - link: /nl/ + name: nl - Nederlands - link: /pl/ name: pl - Polski - link: /pt/ diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md new file mode 100644 index 000000000..8edc3ba0c --- /dev/null +++ b/docs/nl/docs/index.md @@ -0,0 +1,494 @@ +# FastAPI + + + +

          + FastAPI +

          +

          + FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie +

          +

          + + Test + + + Coverage + + + Package version + + + Supported Python versions + +

          + +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Overige sponsoren + +## Meningen + +"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._" + +
          Kabir Khan - Microsoft (ref)
          + +--- + +"_We hebben de **FastAPI** library gebruikt om een **REST** server te maken die bevraagd kan worden om **voorspellingen** te maken. [voor Ludwig]_" + +
          Piero Molino, Yaroslav Dudin en Sai Sumanth Miryala - Uber (ref)
          + +--- + +"_**Netflix** is verheugd om een open-source release aan te kondigen van ons **crisismanagement**-orkestratieframework: **Dispatch**! [gebouwd met **FastAPI**]_" + +
          Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
          + +--- + +"_Ik ben super enthousiast over **FastAPI**. Het is zo leuk!_" + +
          Brian Okken - Python Bytes podcast presentator (ref)
          + +--- + +"_Wat je hebt gebouwd ziet er echt super solide en gepolijst uit. In veel opzichten is het wat ik wilde dat **Hug** kon zijn - het is echt inspirerend om iemand dit te zien bouwen._" + +
          Timothy Crosley - Hug creator (ref)
          + +--- + +"Wie geïnteresseerd is in een **modern framework** voor het bouwen van REST API's, bekijkt best eens **FastAPI** [...] Het is snel, gebruiksvriendelijk en gemakkelijk te leren [...]_" + +"_We zijn overgestapt naar **FastAPI** voor onze **API's** [...] Het gaat jou vast ook bevallen [...]_" + +
          Ines Montani - Matthew Honnibal - Explosion AI oprichters - spaCy ontwikkelaars (ref) - (ref)
          + +--- + +"_Wie een Python API wil bouwen voor productie, kan ik ten stelligste **FastAPI** aanraden. Het is **prachtig ontworpen**, **eenvoudig te gebruiken** en **gemakkelijk schaalbaar**, het is een **cruciale component** geworden in onze strategie om API's centraal te zetten, en het vereenvoudigt automatisering en diensten zoals onze Virtual TAC Engineer._" + +
          Deon Pillsbury - Cisco (ref)
          + +--- + +## **Typer**, de FastAPI van CLIs + + + +Als je een CLI-app bouwt die in de terminal moet worden gebruikt in plaats van een web-API, gebruik dan **Typer**. + +**Typer** is het kleine broertje van FastAPI. En het is bedoeld als de **FastAPI van CLI's**. ️ + +## Vereisten + +FastAPI staat op de schouders van reuzen: + +* Starlette voor de webonderdelen. +* Pydantic voor de datadelen. + +## Installatie + +
          + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
          + +**Opmerking**: Zet `"fastapi[standard]"` tussen aanhalingstekens om ervoor te zorgen dat het werkt in alle terminals. + +## Voorbeeld + +### Creëer het + +* Maak het bestand `main.py` aan met daarin: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
          +Of maak gebruik van async def... + +Als je code gebruik maakt van `async` / `await`, gebruik dan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Opmerking**: + +Als je het niet weet, kijk dan in het gedeelte _"Heb je haast?"_ over `async` en `await` in de documentatie. + +
          + +### Voer het uit + +Run de server met: + +
          + +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
          + +
          +Over het commando fastapi dev main.py... + +Het commando `fastapi dev` leest het `main.py` bestand, detecteert de **FastAPI** app, en start een server met Uvicorn. + +Standaard zal dit commando `fastapi dev` starten met "auto-reload" geactiveerd voor ontwikkeling op het lokale systeem. + +Je kan hier meer over lezen in de FastAPI CLI documentatie. + +
          + +### Controleer het + +Open je browser op http://127.0.0.1:8000/items/5?q=somequery. + +Je zult een JSON response zien: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Je hebt een API gemaakt die: + +* HTTP verzoeken kan ontvangen op de _paden_ `/` en `/items/{item_id}`. +* Beide _paden_ hebben `GET` operaties (ook bekend als HTTP _methoden_). +* Het _pad_ `/items/{item_id}` heeft een _pad parameter_ `item_id` dat een `int` moet zijn. +* Het _pad_ `/items/{item_id}` heeft een optionele `str` _query parameter_ `q`. + +### Interactieve API documentatie + +Ga naar http://127.0.0.1:8000/docs. + +Je ziet de automatische interactieve API documentatie (verstrekt door Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatieve API documentatie + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +Je ziet de automatische interactieve API documentatie (verstrekt door ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Voorbeeld upgrade + +Pas nu het bestand `main.py` aan om de body van een `PUT` request te ontvangen. + +Dankzij Pydantic kunnen we de body declareren met standaard Python types. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +De `fastapi dev` server zou automatisch moeten herladen. + +### Interactieve API documentatie upgrade + +Ga nu naar http://127.0.0.1:8000/docs. + +* De interactieve API-documentatie wordt automatisch bijgewerkt, inclusief de nieuwe body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik op de knop "Try it out", hiermee kan je de parameters invullen en direct met de API interacteren: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Klik vervolgens op de knop "Execute", de gebruikersinterface zal communiceren met jouw API, de parameters verzenden, de resultaten ophalen en deze op het scherm tonen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatieve API documentatie upgrade + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +* De alternatieve documentatie zal ook de nieuwe queryparameter en body weergeven: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Samenvatting + +Samengevat declareer je **eenmalig** de types van parameters, body, etc. als functieparameters. + +Dat doe je met standaard moderne Python types. + +Je hoeft geen nieuwe syntax te leren, de methods of klassen van een specifieke bibliotheek, etc. + +Gewoon standaard **Python**. + +Bijvoorbeeld, voor een `int`: + +```Python +item_id: int +``` + +of voor een complexer `Item` model: + +```Python +item: Item +``` + +...en met die ene verklaring krijg je: + +* Editor ondersteuning, inclusief: + * Code aanvulling. + * Type validatie. +* Validatie van data: + * Automatische en duidelijke foutboodschappen wanneer de data ongeldig is. + * Validatie zelfs voor diep geneste JSON objecten. +* Conversie van invoergegevens: afkomstig van het netwerk naar Python-data en -types. Zoals: + * JSON. + * Pad parameters. + * Query parameters. + * Cookies. + * Headers. + * Formulieren. + * Bestanden. +* Conversie van uitvoergegevens: converstie van Python-data en -types naar netwerkgegevens (zoals JSON): + * Converteer Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objecten. + * `UUID` objecten. + * Database modellen. + * ...en nog veel meer. +* Automatische interactieve API-documentatie, inclusief 2 alternatieve gebruikersinterfaces: + * Swagger UI. + * ReDoc. + +--- + +Terugkomend op het vorige code voorbeeld, **FastAPI** zal: + +* Valideren dat er een `item_id` bestaat in het pad voor `GET` en `PUT` verzoeken. +* Valideren dat het `item_id` van het type `int` is voor `GET` en `PUT` verzoeken. + * Wanneer dat niet het geval is, krijgt de cliënt een nuttige, duidelijke foutmelding. +* Controleren of er een optionele query parameter is met de naam `q` (zoals in `http://127.0.0.1:8000/items/foo?q=somequery`) voor `GET` verzoeken. + * Aangezien de `q` parameter werd gedeclareerd met `= None`, is deze optioneel. + * Zonder de `None` declaratie zou deze verplicht zijn (net als bij de body in het geval met `PUT`). +* Voor `PUT` verzoeken naar `/items/{item_id}`, lees de body als JSON: + * Controleer of het een verplicht attribuut `naam` heeft en dat dat een `str` is. + * Controleer of het een verplicht attribuut `price` heeft en dat dat een`float` is. + * Controleer of het een optioneel attribuut `is_offer` heeft, dat een `bool` is wanneer het aanwezig is. + * Dit alles werkt ook voor diep geneste JSON objecten. +* Converteer automatisch van en naar JSON. +* Documenteer alles met OpenAPI, dat gebruikt kan worden door: + * Interactieve documentatiesystemen. + * Automatische client code generatie systemen, voor vele talen. +* Biedt 2 interactieve documentatie-webinterfaces aan. + +--- + +Dit was nog maar een snel overzicht, maar je zou nu toch al een idee moeten hebben over hoe het allemaal werkt. + +Probeer deze regel te veranderen: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...van: + +```Python + ... "item_name": item.name ... +``` + +...naar: + +```Python + ... "item_price": item.price ... +``` + +...en zie hoe je editor de attributen automatisch invult en hun types herkent: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Voor een vollediger voorbeeld met meer mogelijkheden, zie de Tutorial - Gebruikershandleiding. + +**Spoiler alert**: de tutorial - gebruikershandleiding bevat: + +* Declaratie van **parameters** op andere plaatsen zoals: **headers**, **cookies**, **formuliervelden** en **bestanden**. +* Hoe stel je **validatie restricties** in zoals `maximum_length` of een `regex`. +* Een zeer krachtig en eenvoudig te gebruiken **Dependency Injection** systeem. +* Beveiliging en authenticatie, inclusief ondersteuning voor **OAuth2** met **JWT-tokens** en **HTTP Basic** auth. +* Meer geavanceerde (maar even eenvoudige) technieken voor het declareren van **diep geneste JSON modellen** (dankzij Pydantic). +* **GraphQL** integratie met Strawberry en andere packages. +* Veel extra functies (dankzij Starlette) zoals: + * **WebSockets** + * uiterst gemakkelijke tests gebaseerd op HTTPX en `pytest` + * **CORS** + * **Cookie Sessions** + * ...en meer. + +## Prestaties + +Onafhankelijke TechEmpower benchmarks tonen **FastAPI** applicaties draaiend onder Uvicorn aan als een van de snelste Python frameworks beschikbaar, alleen onder Starlette en Uvicorn zelf (intern gebruikt door FastAPI). (*) + +Zie de sectie Benchmarks om hier meer over te lezen. + +## Afhankelijkheden + +FastAPI maakt gebruik van Pydantic en Starlette. + +### `standard` Afhankelijkheden + +Wanneer je FastAPI installeert met `pip install "fastapi[standard]"`, worden de volgende `standard` optionele afhankelijkheden geïnstalleerd: + +Gebruikt door Pydantic: + +* email_validator - voor email validatie. + +Gebruikt door Starlette: + +* httpx - Vereist indien je de `TestClient` wil gebruiken. +* jinja2 - Vereist als je de standaard templateconfiguratie wil gebruiken. +* python-multipart - Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`. + +Gebruikt door FastAPI / Starlette: + +* uvicorn - voor de server die jouw applicatie laadt en bedient. +* `fastapi-cli` - om het `fastapi` commando te voorzien. + +### Zonder `standard` Afhankelijkheden + +Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`. + +### Bijkomende Optionele Afhankelijkheden + +Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren. + +Bijkomende optionele afhankelijkheden voor Pydantic: + +* pydantic-settings - voor het beheren van settings. +* pydantic-extra-types - voor extra data types die gebruikt kunnen worden met Pydantic. + +Bijkomende optionele afhankelijkheden voor FastAPI: + +* orjson - Vereist indien je `ORJSONResponse` wil gebruiken. +* ujson - Vereist indien je `UJSONResponse` wil gebruiken. + +## Licentie + +Dit project is gelicenseerd onder de voorwaarden van de MIT licentie. diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/nl/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml From ffa6d2eafd8955d3157e77119e07a8b7c09efef2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:44:01 +0000 Subject: [PATCH 163/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 34a3fbc57..6cfbe779b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). ### Internal From 4cf3421178d3ecd909cb393f39e52eed5744e44a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 28 Aug 2024 19:01:29 -0500 Subject: [PATCH 164/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Kong=20(#12085)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index ec7a95497..d8de34e0c 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,6 @@ The key features are: - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 8c0956ac5..76e20638a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -23,9 +23,6 @@ gold: - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png - - url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api - title: Kong Konnect - API management platform - img: https://fastapi.tiangolo.com/img/sponsors/kong.png - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 229cbca71..851f8e895 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -70,12 +70,6 @@
          -
          From 17a29149e4a40dd756f0eb02a9317229e6b3e718 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 29 Aug 2024 00:02:01 +0000 Subject: [PATCH 165/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6cfbe779b..71e7334ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 6e98249c2121959b5253cecc1237ee5438f98758 Mon Sep 17 00:00:00 2001 From: Marcin Sulikowski Date: Fri, 30 Aug 2024 18:00:41 +0200 Subject: [PATCH 166/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20async=20test=20exa?= =?UTF-8?q?mple=20not=20to=20trigger=20DeprecationWarning=20(#12084)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/async-tests.md | 2 +- docs/em/docs/advanced/async-tests.md | 2 +- docs/en/docs/advanced/async-tests.md | 2 +- docs/pt/docs/advanced/async-tests.md | 2 +- docs_src/async_tests/test_main.py | 6 ++++-- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 9f0bd4aa2..e56841faa 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 324b4f68a..11f885fe6 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index ac459ff0c..580d9142c 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note that the test function is now `async def` instead of just `def` as before w Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index ab5bfa648..7cac26262 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py index 9f1527d5f..a57a31f7d 100644 --- a/docs_src/async_tests/test_main.py +++ b/docs_src/async_tests/test_main.py @@ -1,12 +1,14 @@ import pytest -from httpx import AsyncClient +from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): - async with AsyncClient(app=app, base_url="http://test") as ac: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"} From 4eec14fa8c8870898cfa0416b6ff20a724c0dd30 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 30 Aug 2024 16:01:05 +0000 Subject: [PATCH 167/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 71e7334ad..83080e0aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). From 9519380764a371c4c642f969e8f1b82822f7de28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 30 Aug 2024 18:20:21 +0200 Subject: [PATCH 168/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20Coh?= =?UTF-8?q?erence=20(#12093)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/docs/deployment/cloud.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d8de34e0c..5554f71d4 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The key features are: - + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 76e20638a..3a767b6b1 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -17,7 +17,7 @@ gold: - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example + - url: https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index d34fbe2f7..3ea5087f8 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,4 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Coherence +* Coherence From a2458d594facb238f42dc471754612109b5f5c2d Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 30 Aug 2024 16:20:42 +0000 Subject: [PATCH 169/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83080e0aa..2f7fb0cbd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). From 5827b922c3ebf999eae867dbb855c0bf2aa07a7e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 03:23:14 +0000 Subject: [PATCH 170/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f7fb0cbd..d1ac98ed1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). From c37f2c976dfe71ac46ccc082b551d41cb7b6122f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 12:15:50 +0200 Subject: [PATCH 171/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20about=20`ti?= =?UTF-8?q?me.perf=5Fcounter()`=20in=20middlewares=20(#12095)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/middleware.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 06fb3f504..199b593d3 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -63,6 +63,12 @@ For example, you could add a custom header `X-Process-Time` containing the time {!../../../docs_src/middleware/tutorial001.py!} ``` +/// tip + +Here we use `time.perf_counter()` instead of `time.time()` because it can be more precise for these use cases. 🤓 + +/// + ## Other middlewares You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. From 6c8a205db106835c2cd4af5d0b5110f562c2a92f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 10:16:12 +0000 Subject: [PATCH 172/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d1ac98ed1..e0e9192bd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). From 0077af97195ec77ab2fcc5a3cf1536c7ed6125d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 12:18:37 +0200 Subject: [PATCH 173/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20labeler=20confi?= =?UTF-8?q?g=20to=20handle=20sponsorships=20data=20(#12096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index 1d49a2411..c5b1f84f3 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -7,6 +7,8 @@ docs: - all-globs-to-all-files: - '!fastapi/**' - '!pyproject.toml' + - '!docs/en/data/sponsors.yml' + - '!docs/en/overrides/main.html' lang-all: - all: @@ -28,6 +30,8 @@ internal: - .pre-commit-config.yaml - pdm_build.py - requirements*.txt + - docs/en/data/sponsors.yml + - docs/en/overrides/main.html - all-globs-to-all-files: - '!docs/*/docs/**' - '!fastapi/**' From 83422b1923b070da891bfacec707f4d2c796a32c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 10:20:40 +0000 Subject: [PATCH 174/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0e9192bd..a87ce21d4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From eebc6c3d54f96cfd056c0a6fe4de7c3b0064ac42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 17:35:58 +0200 Subject: [PATCH 175/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors=20link?= =?UTF-8?q?:=20Coherence=20(#12097)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/overrides/main.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 851f8e895..47e46c4bf 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -59,7 +59,7 @@
          - + From 47b3351be9c268a3b79faf9b41bf08921dbc8a8b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 15:36:24 +0000 Subject: [PATCH 176/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a87ce21d4..855338742 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 581aacc4a9f3bbb872b082ee55535fe60655de2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:19:30 +0200 Subject: [PATCH 177/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20dependencies=20data=20structures=20with=20dataclasses?= =?UTF-8?q?=20(#12098)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/models.py | 75 ++++++++++++---------------------- fastapi/dependencies/utils.py | 2 +- 2 files changed, 28 insertions(+), 49 deletions(-) diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 61ef00638..418c11725 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,58 +1,37 @@ -from typing import Any, Callable, List, Optional, Sequence +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase +@dataclass class SecurityRequirement: - def __init__( - self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None - ): - self.security_scheme = security_scheme - self.scopes = scopes + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None +@dataclass 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 + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + 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 + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 3e8e7b410..85703c9e9 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -175,7 +175,7 @@ def get_flat_dependant( header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), - security_schemes=dependant.security_requirements.copy(), + security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) From 75c4e7fc44fda0c63d5627af65cb0ba7919fd334 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:19:51 +0000 Subject: [PATCH 178/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 855338742..a02b722f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). From 08547e1d571df8e8cf71d8b15a767acbc38aea62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:27:44 +0200 Subject: [PATCH 179/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20internal=20`analyze=5Fparam()`=20to=20structure=20dat?= =?UTF-8?q?a=20with=20dataclasses=20instead=20of=20tuple=20(#12099)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 85703c9e9..5ebdddaf6 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,7 @@ import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy +from dataclasses import dataclass from typing import ( Any, Callable, @@ -258,16 +259,16 @@ def get_dependant( ) 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_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) - if depends is not None: + if param_details.depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, - depends=depends, + depends=param_details.depends, path=path, security_scopes=security_scopes, ) @@ -275,18 +276,18 @@ def get_dependant( continue if add_non_field_param_to_dependency( param_name=param_name, - type_annotation=type_annotation, + type_annotation=param_details.type_annotation, dependant=dependant, ): assert ( - param_field is None + param_details.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) + assert param_details.field is not None + if is_body_param(param_field=param_details.field, is_path_param=is_path_param): + dependant.body_params.append(param_details.field) else: - add_param_to_fields(field=param_field, dependant=dependant) + add_param_to_fields(field=param_details.field, dependant=dependant) return dependant @@ -314,13 +315,20 @@ def add_non_field_param_to_dependency( return None +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, -) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: +) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any @@ -450,7 +458,7 @@ def analyze_param( field_info=field_info, ) - return type_annotation, depends, field + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: From 8d7d89e8c603ca13043ce037503c66cc6a662a48 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:28:07 +0000 Subject: [PATCH 180/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a02b722f6..677816f40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). ### Docs From 5b7fa3900e3156dcb93f496516740bc06903d7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:52:06 +0200 Subject: [PATCH 181/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20s?= =?UTF-8?q?implify=20internal=20data=20from=20`solve=5Fdependencies()`=20u?= =?UTF-8?q?sing=20dataclasses=20(#12100)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 45 +++++++++++++++++++---------------- fastapi/routing.py | 33 +++++++++++++++---------- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 5ebdddaf6..ed03df88b 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -529,6 +529,15 @@ async def solve_generator( return await stack.enter_async_context(cm) +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + async def solve_dependencies( *, request: Union[Request, WebSocket], @@ -539,13 +548,7 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, -) -> Tuple[ - Dict[str, Any], - List[Any], - Optional[StarletteBackgroundTasks], - Response, - Dict[Tuple[Callable[..., Any], Tuple[str]], Any], -]: +) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: @@ -587,27 +590,21 @@ async def solve_dependencies( dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, ) - ( - 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) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.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): solved = await solve_generator( - call=call, stack=async_exit_stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): - solved = await call(**sub_values) + solved = await call(**solved_result.values) else: - solved = await run_in_threadpool(call, **sub_values) + solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: @@ -654,7 +651,13 @@ async def solve_dependencies( values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) - return values, errors, background_tasks, response, dependency_cache + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) def request_params_to_args( diff --git a/fastapi/routing.py b/fastapi/routing.py index 49f1b6013..c46772017 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -292,26 +292,34 @@ def get_request_handler( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, background_tasks, sub_response, _ = solved_result + errors = solved_result.errors if not errors: raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: - raw_response.background = background_tasks + raw_response.background = solved_result.background_tasks response = raw_response else: - response_args: Dict[str, Any] = {"background": background_tasks} + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( - status_code if status_code else sub_response.status_code + status_code + if status_code + else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) content = await serialize_response( field=response_field, response_content=raw_response, @@ -326,7 +334,7 @@ def get_request_handler( response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) + response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body @@ -360,11 +368,12 @@ def get_websocket_app( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + await dependant.call(**solved_result.values) return app From 3660c7a063ddc605269b0c204acd4724ccf2d69c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:52:29 +0000 Subject: [PATCH 182/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 677816f40..3fc659cbb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). From d08b95ea57fa5740c8c04da554f2b6e259f4dea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 1 Sep 2024 01:46:03 +0200 Subject: [PATCH 183/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Rename=20internal?= =?UTF-8?q?=20`create=5Fresponse=5Ffield()`=20to=20`create=5Fmodel=5Ffield?= =?UTF-8?q?()`=20as=20it's=20used=20for=20more=20than=20response=20models?= =?UTF-8?q?=20(#12103)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 6 +++--- fastapi/routing.py | 6 +++--- fastapi/utils.py | 9 +++------ 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index ed03df88b..c5ed709f7 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -55,7 +55,7 @@ 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 fastapi.utils import create_model_field, get_path_param_names from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -449,7 +449,7 @@ def analyze_param( else: alias = field_info.alias or param_name field_info.alias = alias - field = create_response_field( + field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, @@ -818,7 +818,7 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_response_field( + final_field = create_model_field( name="body", type_=BodyModel, required=required, diff --git a/fastapi/routing.py b/fastapi/routing.py index c46772017..61a112fc4 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -49,7 +49,7 @@ from fastapi.exceptions import ( from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, - create_response_field, + create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, @@ -497,7 +497,7 @@ class APIRoute(routing.Route): status_code ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id - self.response_field = create_response_field( + self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", @@ -530,7 +530,7 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_response_field(name=response_name, type_=model) + response_field = create_model_field(name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields diff --git a/fastapi/utils.py b/fastapi/utils.py index 5c2538fac..4c7350fea 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -60,9 +60,9 @@ def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) -def create_response_field( +def create_model_field( name: str, - type_: Type[Any], + type_: Any, class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, @@ -71,9 +71,6 @@ def create_response_field( alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: - """ - Create a new response field. Raises if type_ is invalid. - """ class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( @@ -135,7 +132,7 @@ def create_cloned_field( use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) - new_field = create_response_field(name=field.name, type_=use_type) + new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] From d5c6cf8122cd8de3d4fcd37b616fbfa2ade1542b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 23:46:26 +0000 Subject: [PATCH 184/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3fc659cbb..d7b278dbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). From 23bda0ffeb26e906b5dcf58423522ab4166669ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 1 Sep 2024 21:39:25 +0200 Subject: [PATCH 185/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20interna?= =?UTF-8?q?l=20`check=5Ffile=5Ffield()`,=20rename=20to=20`ensure=5Fmultipa?= =?UTF-8?q?rt=5Fis=5Finstalled()`=20to=20clarify=20its=20purpose=20(#12106?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 47 ++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index c5ed709f7..0dcba62f1 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -80,25 +80,23 @@ multipart_incorrect_install_error = ( ) -def check_file_field(field: ModelField) -> None: - field_info = field.field_info - if isinstance(field_info, params.Form): +def ensure_multipart_is_installed() -> None: + try: + # __version__ is available in both multiparts, and can be mocked + from multipart import __version__ # type: ignore + + assert __version__ 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 + # 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_not_installed_error) - raise RuntimeError(multipart_not_installed_error) from None + 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( @@ -336,6 +334,7 @@ def analyze_param( if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation + # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] @@ -355,6 +354,7 @@ def analyze_param( ) else: fastapi_annotation = None + # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( @@ -369,9 +369,10 @@ def analyze_param( field_info.default = value else: field_info.default = Required + # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation - + # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" @@ -382,6 +383,7 @@ def analyze_param( f" default value together for {param_name!r}" ) depends = value + # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" @@ -391,11 +393,13 @@ def analyze_param( if PYDANTIC_V2: field_info.annotation = type_annotation + # Get Depends from type annotation if depends is not None and depends.dependency is None: # Copy `depends` before mutating it depends = copy(depends) depends.dependency = type_annotation + # Handle non-param type annotations like Request if lenient_issubclass( type_annotation, ( @@ -411,6 +415,7 @@ def analyze_param( assert ( field_info is None ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value 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: @@ -428,7 +433,9 @@ def analyze_param( field_info = params.Query(annotation=use_annotation, default=default_value) field = None + # It's a field_info, not a dependency if field_info is not None: + # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" @@ -444,6 +451,8 @@ def analyze_param( field_info, param_name, ) + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: @@ -786,7 +795,6 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: 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 @@ -825,5 +833,4 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) - check_file_field(final_field) return final_field From b203d7a15fb5b49635bd81811e09ad94700f68a6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 1 Sep 2024 19:39:46 +0000 Subject: [PATCH 186/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7b278dbe..c3e7c3590 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor internal `check_file_field()`, rename to `ensure_multipart_is_installed()` to clarify its purpose. PR [#12106](https://github.com/fastapi/fastapi/pull/12106) by [@tiangolo](https://github.com/tiangolo). * ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). From 92bdfbc7bac466e502872a1ddf6e7cae069fd068 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Sep 2024 21:36:52 +0200 Subject: [PATCH 187/356] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.9.0=20to=201.10.0=20(#12112)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.9.0 to 1.10.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.9.0...v1.10.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 591df634b..03f87d172 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.9.0 + uses: pypa/gh-action-pypi-publish@v1.10.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 17f1f7b5bde8a75197c3aef7d4d24b04f8438083 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 2 Sep 2024 19:37:19 +0000 Subject: [PATCH 188/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3e7c3590..bc431dfac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). From b63b4189eedc9e586fb51705a0a29ace8fa6a6d1 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Mon, 2 Sep 2024 21:53:53 +0200 Subject: [PATCH 189/356] =?UTF-8?q?=F0=9F=92=9A=20Set=20`include-hidden-fi?= =?UTF-8?q?les`=20to=20`True`=20when=20using=20the=20`upload-artifact`=20G?= =?UTF-8?q?H=20action=20(#12118)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * include-hidden-files when uploading coverage files * include-hidden-files when building docs --- .github/workflows/build-docs.yml | 1 + .github/workflows/test.yml | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index e46629e9b..52c34a49e 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -113,6 +113,7 @@ jobs: with: name: docs-site-${{ matrix.lang }} path: ./site/** + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why docs-all-green: # This job does nothing and is only used for the branch protection diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0458f83ff..e9db49b51 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -91,6 +91,7 @@ jobs: with: name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }} path: coverage + include-hidden-files: true coverage-combine: needs: [test] @@ -123,6 +124,7 @@ jobs: with: name: coverage-html path: htmlcov + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why check: # This job does nothing and is only used for the branch protection From a6ad088183d860c8f985a5e14f916efe77ff5011 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 2 Sep 2024 19:54:19 +0000 Subject: [PATCH 190/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc431dfac..4774f8af9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). From 6b3d1c6d4e84447e310584ee62eaa231636a63d3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:15:17 +0200 Subject: [PATCH 191/356] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2010.3?= =?UTF-8?q?.0=20to=2010.4.0=20(#12105)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.3.0 to 10.4.0. - [Release notes](https://github.com/python-pillow/Pillow/releases) - [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst) - [Commits](https://github.com/python-pillow/Pillow/compare/10.3.0...10.4.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index ab2b0165b..332fd1857 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==10.3.0 +pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 From 7537bac43f1bcbf1edde837422cd4b720317c26b Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:15:41 +0000 Subject: [PATCH 192/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4774f8af9..27900f269 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot). * 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). From c1c57336b04d17077a142ec39724e9fb1a1d8bec Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 3 Sep 2024 10:43:56 -0300 Subject: [PATCH 193/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/security/index.md`=20(#12?= =?UTF-8?q?114)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/security/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 docs/pt/docs/advanced/security/index.md diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md new file mode 100644 index 000000000..ae63f1c96 --- /dev/null +++ b/docs/pt/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Segurança Avançada + +## Funcionalidades Adicionais + +Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +/// tip | "Dica" + +As próximas seções **não são necessariamente "avançadas"**. + +E é possível que para o seu caso de uso, a solução está em uma delas. + +/// + +## Leia o Tutorial primeiro + +As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras. From e26229ed98f8c1e9ccfbf4274157c554e5cd80f3 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 3 Sep 2024 10:44:35 -0300 Subject: [PATCH 194/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/testing-events.md`=20(#12?= =?UTF-8?q?108)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-events.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-events.md diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md new file mode 100644 index 000000000..392fb741c --- /dev/null +++ b/docs/pt/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# Testando Eventos: inicialização - encerramento + +Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: + +```Python hl_lines="9-12 20-24" +{!../../../docs_src/app_testing/tutorial003.py!} +``` From 56cfecc1bfef14506d50eb46b676dc832b85b914 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:44:55 +0000 Subject: [PATCH 195/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 27900f269..2f871a5c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). From 7d69943a22aada657b2326cec43ac6a3023d8203 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:45:21 +0000 Subject: [PATCH 196/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f871a5c4..a9acd0278 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). From 7eae92544351036aa1ab0c70e7dea8e53eae97c9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:47:08 +0200 Subject: [PATCH 197/356] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.10.0=20to=201.10.1=20(#12120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.10.0 to 1.10.1. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.10.0...v1.10.1) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 03f87d172..5004b94dd 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.0 + uses: pypa/gh-action-pypi-publish@v1.10.1 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 560c43269dbd4b3c2964a69cfb1487567dfcb80e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:49:34 +0000 Subject: [PATCH 198/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a9acd0278..a82965aa8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -37,6 +37,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.0 to 1.10.1. PR [#12120](https://github.com/fastapi/fastapi/pull/12120) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot). * 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). From 3feed9dd8c826a11354377c7a81b4d95382413d0 Mon Sep 17 00:00:00 2001 From: Max Scheijen <47034840+maxscheijen@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:50:38 +0200 Subject: [PATCH 199/356] =?UTF-8?q?=F0=9F=8C=90=20=20Add=20Dutch=20transla?= =?UTF-8?q?tion=20for=20`docs/nl/docs/features.md`=20(#12101)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/nl/docs/features.md | 201 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 docs/nl/docs/features.md diff --git a/docs/nl/docs/features.md b/docs/nl/docs/features.md new file mode 100644 index 000000000..848b155ec --- /dev/null +++ b/docs/nl/docs/features.md @@ -0,0 +1,201 @@ +# Functionaliteit + +## FastAPI functionaliteit + +**FastAPI** biedt je het volgende: + +### Gebaseerd op open standaarden + +* OpenAPI voor het maken van API's, inclusief declaraties van padbewerkingen, parameters, request bodies, beveiliging, enz. +* Automatische datamodel documentatie met JSON Schema (aangezien OpenAPI zelf is gebaseerd op JSON Schema). +* Ontworpen op basis van deze standaarden, na zorgvuldig onderzoek. In plaats van achteraf deze laag er bovenop te bouwen. +* Dit maakt het ook mogelijk om automatisch **clientcode te genereren** in verschillende programmeertalen. + +### Automatische documentatie + +Interactieve API-documentatie en verkenning van webgebruikersinterfaces. Aangezien dit framework is gebaseerd op OpenAPI, zijn er meerdere documentatie opties mogelijk, waarvan er standaard 2 zijn inbegrepen. + +* Swagger UI, met interactieve interface, maakt het mogelijk je API rechtstreeks vanuit de browser aan te roepen en te testen. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Alternatieve API-documentatie met ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Gewoon Moderne Python + +Het is allemaal gebaseerd op standaard **Python type** declaraties (dankzij Pydantic). Je hoeft dus geen nieuwe syntax te leren. Het is gewoon standaard moderne Python. + +Als je een opfriscursus van 2 minuten nodig hebt over het gebruik van Python types (zelfs als je FastAPI niet gebruikt), bekijk dan deze korte tutorial: [Python Types](python-types.md){.internal-link target=_blank}. + +Je schrijft gewoon standaard Python met types: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declareer een variabele als een str +# en krijg editorondersteuning in de functie +def main(user_id: str): + return user_id + + +# Een Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +Vervolgens kan je het op deze manier gebruiken: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +/// info + +`**second_user_data` betekent: + +Geef de sleutels (keys) en waarden (values) van de `second_user_data` dict direct door als sleutel-waarden argumenten, gelijk aan: `User(id=4, name=“Mary”, joined=“2018-11-30”)` + +/// + +### Editor-ondersteuning + +Het gehele framework is ontworpen om eenvoudig en intuïtief te zijn in gebruik. Alle beslissingen zijn getest op meerdere code-editors nog voordat het daadwerkelijke ontwikkelen begon, om zo de beste ontwikkelervaring te garanderen. + +Uit enquêtes onder Python ontwikkelaars blijkt maar al te duidelijk dat "(automatische) code aanvulling" een van de meest gebruikte functionaliteiten is. + +Het hele **FastAPI** framework is daarop gebaseerd. Automatische code aanvulling werkt overal. + +Je hoeft zelden terug te vallen op de documentatie. + +Zo kan je editor je helpen: + +* in Visual Studio Code: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* in PyCharm: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Je krijgt autocomletion die je voorheen misschien zelfs voor onmogelijk had gehouden. Zoals bijvoorbeeld de `price` key in een JSON body (die genest had kunnen zijn) die afkomstig is van een request. + +Je hoeft niet langer de verkeerde keys in te typen, op en neer te gaan tussen de documentatie, of heen en weer te scrollen om te checken of je `username` of toch `user_name` had gebruikt. + +### Kort + +Dit framework heeft voor alles verstandige **standaardinstellingen**, met overal optionele configuraties. Alle parameters kunnen worden verfijnd zodat het past bij wat je nodig hebt, om zo de API te kunnen definiëren die jij nodig hebt. + +Maar standaard werkt alles **“gewoon”**. + +### Validatie + +* Validatie voor de meeste (of misschien wel alle?) Python **datatypes**, inclusief: + * JSON objecten (`dict`). + * JSON array (`list`) die itemtypes definiëren. + * String (`str`) velden, die min en max lengtes hebben. + * Getallen (`int`, `float`) met min en max waarden, enz. + +* Validatie voor meer exotische typen, zoals: + * URL. + * E-mail. + * UUID. + * ...en anderen. + +Alle validatie wordt uitgevoerd door het beproefde en robuuste **Pydantic**. + +### Beveiliging en authenticatie + +Beveiliging en authenticatie is geïntegreerd. Zonder compromissen te doen naar databases of datamodellen. + +Alle beveiligingsschema's gedefinieerd in OpenAPI, inclusief: + +* HTTP Basic. +* **OAuth2** (ook met **JWT tokens**). Bekijk de tutorial over [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* API keys in: + * Headers. + * Query parameters. + * Cookies, enz. + +Plus alle beveiligingsfuncties van Starlette (inclusief **sessiecookies**). + +Gebouwd als een herbruikbare tool met componenten die makkelijk te integreren zijn in en met je systemen, datastores, relationele en NoSQL databases, enz. + +### Dependency Injection + +FastAPI bevat een uiterst eenvoudig, maar uiterst krachtig Dependency Injection systeem. + +* Zelfs dependencies kunnen dependencies hebben, waardoor een hiërarchie of **“graph” van dependencies** ontstaat. +* Allemaal **automatisch afgehandeld** door het framework. +* Alle dependencies kunnen data nodig hebben van request, de vereiste **padoperaties veranderen** en automatische documentatie verstrekken. +* **Automatische validatie** zelfs voor *padoperatie* parameters gedefinieerd in dependencies. +* Ondersteuning voor complexe gebruikersauthenticatiesystemen, **databaseverbindingen**, enz. +* **Geen compromisen** met databases, gebruikersinterfaces, enz. Maar eenvoudige integratie met ze allemaal. + +### Ongelimiteerde "plug-ins" + +Of anders gezegd, je hebt ze niet nodig, importeer en gebruik de code die je nodig hebt. + +Elke integratie is ontworpen om eenvoudig te gebruiken (met afhankelijkheden), zodat je een “plug-in" kunt maken in 2 regels code, met dezelfde structuur en syntax die wordt gebruikt voor je *padbewerkingen*. + +### Getest + +* 100% van de code is getest. +* 100% type geannoteerde codebase. +* Wordt gebruikt in productietoepassingen. + +## Starlette functies + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Starlette. + +`FastAPI` is eigenlijk een subklasse van `Starlette`. Dus als je Starlette al kent of gebruikt, zal de meeste functionaliteit op dezelfde manier werken. + +Met **FastAPI** krijg je alle functies van **Starlette** (FastAPI is gewoon Starlette op steroïden): + +* Zeer indrukwekkende prestaties. Het is een van de snelste Python frameworks, vergelijkbaar met **NodeJS** en **Go**. +* **WebSocket** ondersteuning. +* Taken in de achtergrond tijdens het proces. +* Opstart- en afsluit events. +* Test client gebouwd op HTTPX. +* **CORS**, GZip, Statische bestanden, Streaming reacties. +* **Sessie en Cookie** ondersteuning. +* 100% van de code is getest. +* 100% type geannoteerde codebase. + +## Pydantic functionaliteit + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Pydantic. Dus alle extra Pydantic code die je nog hebt werkt ook. + +Inclusief externe pakketten die ook gebaseerd zijn op Pydantic, zoals ORMs, ODMs voor databases. + +Dit betekent ook dat je in veel gevallen het object dat je van een request krijgt **direct naar je database** kunt sturen, omdat alles automatisch wordt gevalideerd. + +Hetzelfde geldt ook andersom, in veel gevallen kun je dus het object dat je krijgt van de database **direct doorgeven aan de client**. + +Met **FastAPI** krijg je alle functionaliteit van **Pydantic** (omdat FastAPI is gebaseerd op Pydantic voor alle dataverwerking): + +* **Geen brainfucks**: + * Je hoeft geen nieuwe microtaal voor schemadefinities te leren. + * Als je bekend bent Python types, weet je hoe je Pydantic moet gebruiken. +* Werkt goed samen met je **IDE/linter/hersenen**: + * Doordat pydantic's datastructuren enkel instanties zijn van klassen, die je definieert, werkt automatische aanvulling, linting, mypy en je intuïtie allemaal goed met je gevalideerde data. +* Valideer **complexe structuren**: + * Gebruik van hiërarchische Pydantic modellen, Python `typing`'s `List` en `Dict`, enz. + * Met validators kunnen complexe dataschema's duidelijk en eenvoudig worden gedefinieerd, gecontroleerd en gedocumenteerd als JSON Schema. + * Je kunt diep **geneste JSON** objecten laten valideren en annoteren. +* **Uitbreidbaar**: + * Met Pydantic kunnen op maat gemaakte datatypen worden gedefinieerd of je kunt validatie uitbreiden met methoden op een model dat is ingericht met de decorator validator. +* 100% van de code is getest. From cbdc58b1b75a7e94c78d3dca39f0564bd071d190 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:54:00 +0000 Subject: [PATCH 200/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a82965aa8..df4927752 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/features.md`. PR [#12101](https://github.com/fastapi/fastapi/pull/12101) by [@maxscheijen](https://github.com/maxscheijen). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). From f42fd9aac2529c1bda6b81fe9cecce0986dadbf3 Mon Sep 17 00:00:00 2001 From: Shubhendra Kushwaha Date: Tue, 3 Sep 2024 21:35:19 +0530 Subject: [PATCH 201/356] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Techniques=20and=20applications=20of=20SQLAlchemy=20global?= =?UTF-8?q?=20filters=20in=20FastAPI=20(#12109)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 15f6169ee..63fd3d0cf 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -264,6 +264,14 @@ Articles: author_link: https://devonray.com link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/mastering-soft-delete-advanced-sqlalchemy-techniques-4678f4738947 + title: 'Mastering Soft Delete: Advanced SQLAlchemy Techniques' + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/role-based-row-filtering-advanced-sqlalchemy-techniques-733e6b1328f6 + title: 'Role based row filtering: Advanced SQLAlchemy Techniques' German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com From 9b2a9333b3b9820082deb35605c0619bd578baee Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 16:05:42 +0000 Subject: [PATCH 202/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index df4927752..70dbce539 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Docs +* 📝 Add External Link: Techniques and applications of SQLAlchemy global filters in FastAPI. PR [#12109](https://github.com/fastapi/fastapi/pull/12109) by [@TheShubhendra](https://github.com/TheShubhendra). * 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). From 1f64a1bb551829b57f0b8403ce4aab641a6ee11d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 5 Sep 2024 11:07:32 +0200 Subject: [PATCH 203/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12115)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ⬆ [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.2 → v0.6.3](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.2...v0.6.3) * bump ruff as well --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem Co-authored-by: svlandeg --- .pre-commit-config.yaml | 2 +- requirements-tests.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 317514062..7e58afd4b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.2 + rev: v0.6.3 hooks: - id: ruff args: diff --git a/requirements-tests.txt b/requirements-tests.txt index 08561d23a..de5fdb8a2 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.6.1 +ruff ==0.6.3 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel From 68e5ef6968f8a2799d9db927b5db5b8e86d8b5f0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 09:07:55 +0000 Subject: [PATCH 204/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 70dbce539..c54971b73 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -39,6 +39,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12115](https://github.com/fastapi/fastapi/pull/12115) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.0 to 1.10.1. PR [#12120](https://github.com/fastapi/fastapi/pull/12120) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot). * 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). From 7213d421f5bf0a4b9b8815e69a141550b4fc3f09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 11:13:32 +0200 Subject: [PATCH 205/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ fastapi/__init__.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c54971b73..cdd6cdc90 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +## 0.112.3 + +This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀 + ### Refactors * ♻️ Refactor internal `check_file_field()`, rename to `ensure_multipart_is_installed()` to clarify its purpose. PR [#12106](https://github.com/fastapi/fastapi/pull/12106) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index ac2508d89..1bc1bfd82 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.2" +__version__ = "0.112.3" from starlette import status as status From aa21814a89853c17c139054a5c51f0bb1ea68a0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 13:24:36 +0200 Subject: [PATCH 206/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20decidin?= =?UTF-8?q?g=20if=20`embed`=20body=20fields,=20do=20not=20overwrite=20fiel?= =?UTF-8?q?ds,=20compute=20once=20per=20router,=20refactor=20internals=20i?= =?UTF-8?q?n=20preparation=20for=20Pydantic=20models=20in=20`Form`,=20`Que?= =?UTF-8?q?ry`=20and=20others=20(#12117)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/_compat.py | 15 ++ fastapi/dependencies/utils.py | 300 ++++++++++++++++++------------- fastapi/param_functions.py | 4 +- fastapi/params.py | 3 +- fastapi/routing.py | 26 ++- tests/test_compat.py | 13 +- tests/test_forms_single_param.py | 99 ++++++++++ 7 files changed, 324 insertions(+), 136 deletions(-) create mode 100644 tests/test_forms_single_param.py diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 06b847b4f..f940d6597 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -279,6 +279,12 @@ if PYDANTIC_V2: BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return [ + ModelField(field_info=field_info, name=name) + for name, field_info in model.model_fields.items() + ] + else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 @@ -513,6 +519,9 @@ else: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return list(model.__fields__.values()) # type: ignore[attr-defined] + def _regenerate_error_with_loc( *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...] @@ -532,6 +541,12 @@ def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if field_annotation_is_sequence(arg): + return True + return False return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 0dcba62f1..7ac18d941 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -59,7 +59,13 @@ from fastapi.utils import create_model_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.datastructures import ( + FormData, + Headers, + ImmutableMultiDict, + QueryParams, + UploadFile, +) from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket @@ -282,7 +288,7 @@ def get_dependant( ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue assert param_details.field is not None - if is_body_param(param_field=param_details.field, is_path_param=is_path_param): + if isinstance(param_details.field.field_info, params.Body): dependant.body_params.append(param_details.field) else: add_param_to_fields(field=param_details.field, dependant=dependant) @@ -466,29 +472,16 @@ def analyze_param( required=field_info.default in (Required, Undefined), field_info=field_info, ) + if is_path_param: + assert is_scalar_field( + field=field + ), "Path params must be of one of the supported types" + elif isinstance(field_info, params.Query): + assert is_scalar_field(field) or is_scalar_sequence_field(field) return ParamDetails(type_annotation=type_annotation, depends=depends, field=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 = field.field_info field_info_in = getattr(field_info, "in_", None) @@ -557,6 +550,7 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, + embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] @@ -598,6 +592,7 @@ async def solve_dependencies( dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) background_tasks = solved_result.background_tasks dependency_cache.update(solved_result.dependency_cache) @@ -640,7 +635,9 @@ async def solve_dependencies( body_values, body_errors, ) = await request_body_to_args( # body_params checked above - required_params=dependant.body_params, received_body=body + body_fields=dependant.body_params, + received_body=body, + embed_body_fields=embed_body_fields, ) values.update(body_values) errors.extend(body_errors) @@ -669,138 +666,185 @@ async def solve_dependencies( ) +def _validate_value_with_model_field( + *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...] +) -> Tuple[Any, List[Any]]: + if value is None: + if field.required: + return None, [get_missing_field_error(loc=loc)] + else: + return deepcopy(field.default), [] + v_, errors_ = field.validate(value, values, loc=loc) + if isinstance(errors_, ErrorWrapper): + return None, [errors_] + elif isinstance(errors_, list): + new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) + return None, new_errors + else: + return v_, [] + + +def _get_multidict_value(field: ModelField, values: Mapping[str, Any]) -> Any: + if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): + value = values.getlist(field.alias) + else: + value = values.get(field.alias, None) + if ( + value is None + or ( + isinstance(field.field_info, params.Form) + and isinstance(value, str) # For type checks + and value == "" + ) + or (is_sequence_field(field) and len(value) == 0) + ): + if field.required: + return + else: + return deepcopy(field.default) + return value + + def request_params_to_args( - required_params: Sequence[ModelField], + fields: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[Any]]: - values = {} + values: Dict[str, Any] = {} 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) + for field in fields: + value = _get_multidict_value(field, received_params) 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) + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) else: values[field.name] = v_ return values, errors +def _should_embed_body_fields(fields: List[ModelField]) -> bool: + if not fields: + return False + # More than one dependency could have the same field, it would show up as multiple + # fields but it's the same one, so count them by name + body_param_names_set = {field.name for field in fields} + # A top level field has to be a single field, not multiple + if len(body_param_names_set) > 1: + return True + first_field = fields[0] + # If it explicitly specifies it is embedded, it has to be embedded + if getattr(first_field.field_info, "embed", None): + return True + # If it's a Form (or File) field, it has to be a BaseModel to be top level + # otherwise it has to be embedded, so that the key value pair can be extracted + if isinstance(first_field.field_info, params.Form): + return True + return False + + +async def _extract_form_body( + body_fields: List[ModelField], + received_body: FormData, +) -> Dict[str, Any]: + values = {} + first_field = body_fields[0] + first_field_info = first_field.field_info + + for field in body_fields: + value = _get_multidict_value(field, received_body) + if ( + isinstance(first_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(first_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) + values[field.name] = value + return values + + async def request_body_to_args( - required_params: List[ModelField], + body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], + embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: - values = {} + values: Dict[str, Any] = {} 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) + assert body_fields, "request_body_to_args() should be called with fields" + single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields + first_field = body_fields[0] + body_to_process = received_body + if isinstance(received_body, FormData): + body_to_process = await _extract_form_body(body_fields, received_body) + + if single_not_embedded_field: + loc: Tuple[str, ...] = ("body",) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=body_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in body_fields: + loc = ("body", field.alias) + value: Optional[Any] = None + if body_to_process is not None: + try: + value = body_to_process.get(field.alias) + # If the received body is a list, not a dict + except AttributeError: + errors.append(get_missing_field_error(loc)) 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_ + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(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) +def get_body_field( + *, flat_dependant: Dependant, name: str, embed_body_fields: bool +) -> Optional[ModelField]: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ 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: + if not embed_body_fields: 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 diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 0d5f27af4..7ddaace25 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -1282,7 +1282,7 @@ def Body( # noqa: N802 ), ] = _Unset, embed: Annotated[ - bool, + Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a @@ -1294,7 +1294,7 @@ def Body( # noqa: N802 [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), - ] = False, + ] = None, media_type: Annotated[ str, Doc( diff --git a/fastapi/params.py b/fastapi/params.py index cc2a5c13c..3dfa5a1a3 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -479,7 +479,7 @@ class Body(FieldInfo): *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, - embed: bool = False, + embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, @@ -642,7 +642,6 @@ class Form(Body): default=default, default_factory=default_factory, annotation=annotation, - embed=True, media_type=media_type, alias=alias, alias_priority=alias_priority, diff --git a/fastapi/routing.py b/fastapi/routing.py index 61a112fc4..86e303602 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -33,8 +33,10 @@ from fastapi._compat import ( from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( + _should_embed_body_fields, get_body_field, get_dependant, + get_flat_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, @@ -225,6 +227,7 @@ def get_request_handler( response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) @@ -291,6 +294,7 @@ def get_request_handler( body=body, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) errors = solved_result.errors if not errors: @@ -354,7 +358,9 @@ def get_request_handler( def get_websocket_app( - dependant: Dependant, dependency_overrides_provider: Optional[Any] = None + dependant: Dependant, + dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: async with AsyncExitStack() as async_exit_stack: @@ -367,6 +373,7 @@ def get_websocket_app( dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) if solved_result.errors: raise WebSocketRequestValidationError( @@ -399,11 +406,15 @@ class APIWebSocketRoute(routing.WebSocketRoute): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) ) @@ -544,7 +555,15 @@ class APIRoute(routing.Route): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.body_field = get_body_field( + flat_dependant=self._flat_dependant, + name=self.unique_id, + embed_body_fields=self._embed_body_fields, + ) self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: @@ -561,6 +580,7 @@ class APIRoute(routing.Route): response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) def matches(self, scope: Scope) -> Tuple[Match, Scope]: diff --git a/tests/test_compat.py b/tests/test_compat.py index bf268b860..270475bf3 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -1,11 +1,13 @@ -from typing import List, Union +from typing import Any, Dict, List, Union from fastapi import FastAPI, UploadFile from fastapi._compat import ( ModelField, Undefined, _get_model_config, + get_model_fields, is_bytes_sequence_annotation, + is_scalar_field, is_uploadfile_sequence_annotation, ) from fastapi.testclient import TestClient @@ -91,3 +93,12 @@ def test_is_uploadfile_sequence_annotation(): # and other types, but I'm not even sure it's a good idea to support it as a first # class "feature" assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]]) + + +def test_is_pv1_scalar_field(): + # For coverage + class Model(BaseModel): + foo: Union[str, Dict[str, Any]] + + fields = get_model_fields(Model) + assert not is_scalar_field(fields[0]) diff --git a/tests/test_forms_single_param.py b/tests/test_forms_single_param.py new file mode 100644 index 000000000..3bb951441 --- /dev/null +++ b/tests/test_forms_single_param.py @@ -0,0 +1,99 @@ +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/form/") +def post_form(username: Annotated[str, Form()]): + return username + + +client = TestClient(app) + + +def test_single_form_field(): + response = client.post("/form/", data={"username": "Rick"}) + assert response.status_code == 200, response.text + assert response.json() == "Rick" + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/form/": { + "post": { + "summary": "Post Form", + "operationId": "post_form_form__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_post_form_form__post" + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "Body_post_form_form__post": { + "properties": {"username": {"type": "string", "title": "Username"}}, + "type": "object", + "required": ["username"], + "title": "Body_post_form_form__post", + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } From 832e634fd4b8c4e1a5714b5ad73f2cdc04e05e43 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 11:25:02 +0000 Subject: [PATCH 207/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cdd6cdc90..2fe884615 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.3 This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀 From 0f3e65b00712a59d763cf9c7715cde353bb94b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 16:40:48 +0200 Subject: [PATCH 208/356] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20Pydan?= =?UTF-8?q?tic=20models=20in=20`Form`=20parameters=20(#12127)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/request-form-models/image01.png | Bin 0 -> 44487 bytes docs/en/docs/tutorial/request-form-models.md | 65 +++++ docs/en/mkdocs.yml | 1 + docs_src/request_form_models/tutorial001.py | 14 + .../request_form_models/tutorial001_an.py | 15 ++ .../tutorial001_an_py39.py | 16 ++ fastapi/dependencies/utils.py | 17 +- .../playwright/request_form_models/image01.py | 36 +++ tests/test_forms_single_model.py | 129 ++++++++++ .../test_request_form_models/__init__.py | 0 .../test_tutorial001.py | 232 +++++++++++++++++ .../test_tutorial001_an.py | 232 +++++++++++++++++ .../test_tutorial001_an_py39.py | 240 ++++++++++++++++++ 13 files changed, 994 insertions(+), 3 deletions(-) create mode 100644 docs/en/docs/img/tutorial/request-form-models/image01.png create mode 100644 docs/en/docs/tutorial/request-form-models.md create mode 100644 docs_src/request_form_models/tutorial001.py create mode 100644 docs_src/request_form_models/tutorial001_an.py create mode 100644 docs_src/request_form_models/tutorial001_an_py39.py create mode 100644 scripts/playwright/request_form_models/image01.py create mode 100644 tests/test_forms_single_model.py create mode 100644 tests/test_tutorial/test_request_form_models/__init__.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py diff --git a/docs/en/docs/img/tutorial/request-form-models/image01.png b/docs/en/docs/img/tutorial/request-form-models/image01.png new file mode 100644 index 0000000000000000000000000000000000000000..3fe32c03d589e76abec5e9c6b71374ebd4e8cd2c GIT binary patch literal 44487 zcmeFZcT|(j_b-b2Dz8{DDj*>68l^Ys(k&DL0RgF@_uhL8ib&{6RjSe3GerJ&n@emd;U6qoOQFZ);yV+XJ+p`lX>?3?7g3`_bT#tDCj82$jI&} zyp>TWBfCz#ygKyvRbugyN%0D?xZ(r=sS4^yATZ0)ghX z0GGhuk!4}GYJ%u$g6MO9t>3pz-qDliELRCcS^I8pie4O=Wek*=8TIyP`lz4jLD1fKsp$iDphv_MXSl#dKWT2O9^ z%Lx`$sAy=k!72(0wNw)9#NMG=CdYZQ zE~Mg!Zftr(!AO~sUW>G~7lmI4de6K%a^2iK*m1!|g!2jw>`3U!Qu^BTIbVs_lWm4mk{>>lazmr6t~~;<}0!)J88oGYQo}hN0Sr6 za9%D7Qs-2Fy<}8er zTQjemmqFq?-UK!QE;u^I&YU%#@mNd=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#hI5MhbD9ql-eF#=LSO zKRJ5<4c8=+)4wB5Mne^-QuO4-`~Lz+ CMaG{1 literal 0 HcmV?d00001 diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..8bb1ffb1f --- /dev/null +++ b/docs/en/docs/tutorial/request-form-models.md @@ -0,0 +1,65 @@ +# Form Models + +You can use Pydantic models to declare form fields in FastAPI. + +/// info + +To use forms, first install `python-multipart`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` + +/// + +/// note + +This is supported since FastAPI version `0.113.0`. 🤓 + +/// + +## Pydantic Models for Forms + +You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9-11 15" +{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-10 14" +{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7-9 13" +{!> ../../../docs_src/request_form_models/tutorial001.py!} +``` + +//// + +FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined. + +## Check the Docs + +You can verify it in the docs UI at `/docs`: + +
          + +
          diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 528c80b8e..7c810c2d7 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -129,6 +129,7 @@ nav: - tutorial/extra-models.md - tutorial/response-status-code.md - tutorial/request-forms.md + - tutorial/request-form-models.md - tutorial/request-files.md - tutorial/request-forms-and-files.md - tutorial/handling-errors.md diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py new file mode 100644 index 000000000..98feff0b9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py new file mode 100644 index 000000000..30483d445 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py new file mode 100644 index 000000000..7cc81aae9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an_py39.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 7ac18d941..98ce17b55 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -33,6 +33,7 @@ from fastapi._compat import ( field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, + get_model_fields, is_bytes_field, is_bytes_sequence_field, is_scalar_field, @@ -56,6 +57,7 @@ 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_model_field, get_path_param_names +from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -743,7 +745,9 @@ def _should_embed_body_fields(fields: List[ModelField]) -> bool: return True # If it's a Form (or File) field, it has to be a BaseModel to be top level # otherwise it has to be embedded, so that the key value pair can be extracted - if isinstance(first_field.field_info, params.Form): + if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( + first_field.type_, BaseModel + ): return True return False @@ -783,7 +787,8 @@ async def _extract_form_body( for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) - values[field.name] = value + if value is not None: + values[field.name] = value return values @@ -798,8 +803,14 @@ async def request_body_to_args( single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body + + fields_to_extract: List[ModelField] = body_fields + + if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_model_fields(first_field.type_) + if isinstance(received_body, FormData): - body_to_process = await _extract_form_body(body_fields, received_body) + body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py new file mode 100644 index 000000000..15bd3858c --- /dev/null +++ b/scripts/playwright/request_form_models/image01.py @@ -0,0 +1,36 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="POST /login/ Login").click() + page.get_by_role("button", name="Try it out").click() + page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py new file mode 100644 index 000000000..7ed3ba3a2 --- /dev/null +++ b/tests/test_forms_single_model.py @@ -0,0 +1,129 @@ +from typing import List, Optional + +from dirty_equals import IsDict +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormModel(BaseModel): + username: str + lastname: str + age: Optional[int] = None + tags: List[str] = ["foo", "bar"] + + +@app.post("/form/") +def post_form(user: Annotated[FormModel, Form()]): + return user + + +client = TestClient(app) + + +def test_send_all_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "70", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": 70, + "tags": ["plumbus", "citadel"], + } + + +def test_defaults(): + response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": None, + "tags": ["foo", "bar"], + } + + +def test_invalid_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "seventy", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "age"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "seventy", + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "age"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_no_data(): + response = client.post("/form/") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"]}, + }, + { + "type": "missing", + "loc": ["body", "lastname"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"]}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "lastname"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) diff --git a/tests/test_tutorial/test_request_form_models/__init__.py b/tests/test_tutorial/test_request_form_models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py new file mode 100644 index 000000000..46c130ee8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001 import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py new file mode 100644 index 000000000..4e14d89c8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py new file mode 100644 index 000000000..2e6426aa7 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py @@ -0,0 +1,240 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from tests.utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } From ccb19c4c3506d7cb05218076d0e3527cb21eed81 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 14:41:11 +0000 Subject: [PATCH 209/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2fe884615..8fe8be6a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Features + +* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). + ### Refactors * ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo). From 8e6cf9ee9c9d87b6b658cc240146121c80f71476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 16:55:44 +0200 Subject: [PATCH 210/356] =?UTF-8?q?=E2=8F=AA=EF=B8=8F=20Temporarily=20reve?= =?UTF-8?q?rt=20"=E2=9C=A8=20Add=20support=20for=20Pydantic=20models=20in?= =?UTF-8?q?=20`Form`=20parameters"=20to=20make=20a=20checkpoint=20release?= =?UTF-8?q?=20(#12128)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revert "✨ Add support for Pydantic models in `Form` parameters (#12127)" This reverts commit 0f3e65b00712a59d763cf9c7715cde353bb94b02. --- .../tutorial/request-form-models/image01.png | Bin 44487 -> 0 bytes docs/en/docs/tutorial/request-form-models.md | 65 ----- docs/en/mkdocs.yml | 1 - docs_src/request_form_models/tutorial001.py | 14 - .../request_form_models/tutorial001_an.py | 15 -- .../tutorial001_an_py39.py | 16 -- fastapi/dependencies/utils.py | 17 +- .../playwright/request_form_models/image01.py | 36 --- tests/test_forms_single_model.py | 129 ---------- .../test_request_form_models/__init__.py | 0 .../test_tutorial001.py | 232 ----------------- .../test_tutorial001_an.py | 232 ----------------- .../test_tutorial001_an_py39.py | 240 ------------------ 13 files changed, 3 insertions(+), 994 deletions(-) delete mode 100644 docs/en/docs/img/tutorial/request-form-models/image01.png delete mode 100644 docs/en/docs/tutorial/request-form-models.md delete mode 100644 docs_src/request_form_models/tutorial001.py delete mode 100644 docs_src/request_form_models/tutorial001_an.py delete mode 100644 docs_src/request_form_models/tutorial001_an_py39.py delete mode 100644 scripts/playwright/request_form_models/image01.py delete mode 100644 tests/test_forms_single_model.py delete mode 100644 tests/test_tutorial/test_request_form_models/__init__.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py diff --git a/docs/en/docs/img/tutorial/request-form-models/image01.png b/docs/en/docs/img/tutorial/request-form-models/image01.png deleted file mode 100644 index 3fe32c03d589e76abec5e9c6b71374ebd4e8cd2c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 44487 zcmeFZcT|(j_b-b2Dz8{DDj*>68l^Ys(k&DL0RgF@_uhL8ib&{6RjSe3GerJ&n@emd;U6qoOQFZ);yV+XJ+p`lX>?3?7g3`_bT#tDCj82$jI&} zyp>TWBfCz#ygKyvRbugyN%0D?xZ(r=sS4^yATZ0)ghX z0GGhuk!4}GYJ%u$g6MO9t>3pz-qDliELRCcS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781$9wP(ZB+ugZ97%#vu&cY?24J(R@a9OttC+m%j82Dx)G_`WO!kS8% zR;Hs(71gDZ3AsOlG?-gQyvQUH>lvoz??p(JDTQh4*_j;1F@Ax-US-#6#_ty8YAY%# zUS<=i*-ZTK;e+7miV<6bor8k`;qv*T%c>v#iN#v&#`*419~Y$FaPkC%?|qBSj-bk} z9Oi`F)%+}wgBp|;9v;qh3REDGNK{2J$DJ&O@<0ATH4FbQe#hI5MhbD9ql-eF#=LSO zKRJ5<4c8=+)4wB5Mne^-QuO4-`~Lz+ CMaG{1 diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md deleted file mode 100644 index 8bb1ffb1f..000000000 --- a/docs/en/docs/tutorial/request-form-models.md +++ /dev/null @@ -1,65 +0,0 @@ -# Form Models - -You can use Pydantic models to declare form fields in FastAPI. - -/// info - -To use forms, first install `python-multipart`. - -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: - -```console -$ pip install python-multipart -``` - -/// - -/// note - -This is supported since FastAPI version `0.113.0`. 🤓 - -/// - -## Pydantic Models for Forms - -You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as `Form`: - -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-9 13" -{!> ../../../docs_src/request_form_models/tutorial001.py!} -``` - -//// - -FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined. - -## Check the Docs - -You can verify it in the docs UI at `/docs`: - -
          - -
          diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 7c810c2d7..528c80b8e 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -129,7 +129,6 @@ nav: - tutorial/extra-models.md - tutorial/response-status-code.md - tutorial/request-forms.md - - tutorial/request-form-models.md - tutorial/request-files.md - tutorial/request-forms-and-files.md - tutorial/handling-errors.md diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py deleted file mode 100644 index 98feff0b9..000000000 --- a/docs_src/request_form_models/tutorial001.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI, Form -from pydantic import BaseModel - -app = FastAPI() - - -class FormData(BaseModel): - username: str - password: str - - -@app.post("/login/") -async def login(data: FormData = Form()): - return data diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py deleted file mode 100644 index 30483d445..000000000 --- a/docs_src/request_form_models/tutorial001_an.py +++ /dev/null @@ -1,15 +0,0 @@ -from fastapi import FastAPI, Form -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - - -class FormData(BaseModel): - username: str - password: str - - -@app.post("/login/") -async def login(data: Annotated[FormData, Form()]): - return data diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py deleted file mode 100644 index 7cc81aae9..000000000 --- a/docs_src/request_form_models/tutorial001_an_py39.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Form -from pydantic import BaseModel - -app = FastAPI() - - -class FormData(BaseModel): - username: str - password: str - - -@app.post("/login/") -async def login(data: Annotated[FormData, Form()]): - return data diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 98ce17b55..7ac18d941 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -33,7 +33,6 @@ from fastapi._compat import ( field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, - get_model_fields, is_bytes_field, is_bytes_sequence_field, is_scalar_field, @@ -57,7 +56,6 @@ 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_model_field, get_path_param_names -from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -745,9 +743,7 @@ def _should_embed_body_fields(fields: List[ModelField]) -> bool: return True # If it's a Form (or File) field, it has to be a BaseModel to be top level # otherwise it has to be embedded, so that the key value pair can be extracted - if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( - first_field.type_, BaseModel - ): + if isinstance(first_field.field_info, params.Form): return True return False @@ -787,8 +783,7 @@ async def _extract_form_body( for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) - if value is not None: - values[field.name] = value + values[field.name] = value return values @@ -803,14 +798,8 @@ async def request_body_to_args( single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body - - fields_to_extract: List[ModelField] = body_fields - - if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): - fields_to_extract = get_model_fields(first_field.type_) - if isinstance(received_body, FormData): - body_to_process = await _extract_form_body(fields_to_extract, received_body) + body_to_process = await _extract_form_body(body_fields, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py deleted file mode 100644 index 15bd3858c..000000000 --- a/scripts/playwright/request_form_models/image01.py +++ /dev/null @@ -1,36 +0,0 @@ -import subprocess -import time - -import httpx -from playwright.sync_api import Playwright, sync_playwright - - -# Run playwright codegen to generate the code below, copy paste the sections in run() -def run(playwright: Playwright) -> None: - browser = playwright.chromium.launch(headless=False) - context = browser.new_context() - page = context.new_page() - page.goto("http://localhost:8000/docs") - page.get_by_role("button", name="POST /login/ Login").click() - page.get_by_role("button", name="Try it out").click() - page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") - - # --------------------- - context.close() - browser.close() - - -process = subprocess.Popen( - ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] -) -try: - for _ in range(3): - try: - response = httpx.get("http://localhost:8000/docs") - except httpx.ConnectError: - time.sleep(1) - break - with sync_playwright() as playwright: - run(playwright) -finally: - process.terminate() diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py deleted file mode 100644 index 7ed3ba3a2..000000000 --- a/tests/test_forms_single_model.py +++ /dev/null @@ -1,129 +0,0 @@ -from typing import List, Optional - -from dirty_equals import IsDict -from fastapi import FastAPI, Form -from fastapi.testclient import TestClient -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - - -class FormModel(BaseModel): - username: str - lastname: str - age: Optional[int] = None - tags: List[str] = ["foo", "bar"] - - -@app.post("/form/") -def post_form(user: Annotated[FormModel, Form()]): - return user - - -client = TestClient(app) - - -def test_send_all_data(): - response = client.post( - "/form/", - data={ - "username": "Rick", - "lastname": "Sanchez", - "age": "70", - "tags": ["plumbus", "citadel"], - }, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "Rick", - "lastname": "Sanchez", - "age": 70, - "tags": ["plumbus", "citadel"], - } - - -def test_defaults(): - response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "Rick", - "lastname": "Sanchez", - "age": None, - "tags": ["foo", "bar"], - } - - -def test_invalid_data(): - response = client.post( - "/form/", - data={ - "username": "Rick", - "lastname": "Sanchez", - "age": "seventy", - "tags": ["plumbus", "citadel"], - }, - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["body", "age"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "seventy", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "age"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -def test_no_data(): - response = client.post("/form/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"tags": ["foo", "bar"]}, - }, - { - "type": "missing", - "loc": ["body", "lastname"], - "msg": "Field required", - "input": {"tags": ["foo", "bar"]}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "lastname"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) diff --git a/tests/test_tutorial/test_request_form_models/__init__.py b/tests/test_tutorial/test_request_form_models/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py deleted file mode 100644 index 46c130ee8..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001.py +++ /dev/null @@ -1,232 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001 import app - - client = TestClient(app) - return client - - -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py deleted file mode 100644 index 4e14d89c8..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py +++ /dev/null @@ -1,232 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py deleted file mode 100644 index 2e6426aa7..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py +++ /dev/null @@ -1,240 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from tests.utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From b69e8b24af305ddceaa9c63c8d2eebf80672caed Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 14:56:10 +0000 Subject: [PATCH 211/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8fe8be6a7..3c5fbb731 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,10 @@ hide: * ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo). +### Internal + +* ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.3 This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀 From 8224addd8f31325ad465af994da8421a69f494ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 16:57:57 +0200 Subject: [PATCH 212/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3c5fbb731..22a224a5a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,7 +9,7 @@ hide: ### Features -* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). +## 0.112.4 ### Refactors @@ -18,6 +18,7 @@ hide: ### Internal * ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). +* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). Reverted to make a checkpoint release with only refactors. ## 0.112.3 From 96c7e7e0f34730e6f6333ced9476bfd62f384cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:00:13 +0200 Subject: [PATCH 213/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 22a224a5a..43ce86c99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,10 +7,12 @@ hide: ## Latest Changes -### Features - ## 0.112.4 +This release is mainly a big internal refactor to enable adding support for Pydantic models for `Form` fields, but that feature comes in the next release. + +This release shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. It's just a checkpoint. 🤓 + ### Refactors * ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo). From 999eeb6c76ff37f94612dd140ce8091932f56c54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:00:33 +0200 Subject: [PATCH 214/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?2.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 1bc1bfd82..1e10bf557 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.3" +__version__ = "0.112.4" from starlette import status as status From 965fc8301e8fa7a7228bee33873387f4852a30df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:09:31 +0200 Subject: [PATCH 215/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 43ce86c99..9b44bc9a8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,8 +19,8 @@ This release shouldn't affect apps using FastAPI in any way. You don't even have ### Internal -* ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). -* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). Reverted to make a checkpoint release with only refactors. +* ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129). +* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). Reverted by PR [#12128](https://github.com/fastapi/fastapi/pull/12128) to make a checkpoint release with only refactors. Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129). ## 0.112.3 From 7bad7c09757f8a06cf62cc0838082a766065883e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:16:50 +0200 Subject: [PATCH 216/356] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20Pydan?= =?UTF-8?q?tic=20models=20in=20`Form`=20parameters=20(#12129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revert "⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` pa…" This reverts commit 8e6cf9ee9c9d87b6b658cc240146121c80f71476. --- .../tutorial/request-form-models/image01.png | Bin 0 -> 44487 bytes docs/en/docs/tutorial/request-form-models.md | 65 +++++ docs/en/mkdocs.yml | 1 + docs_src/request_form_models/tutorial001.py | 14 + .../request_form_models/tutorial001_an.py | 15 ++ .../tutorial001_an_py39.py | 16 ++ fastapi/dependencies/utils.py | 17 +- .../playwright/request_form_models/image01.py | 36 +++ tests/test_forms_single_model.py | 129 ++++++++++ .../test_request_form_models/__init__.py | 0 .../test_tutorial001.py | 232 +++++++++++++++++ .../test_tutorial001_an.py | 232 +++++++++++++++++ .../test_tutorial001_an_py39.py | 240 ++++++++++++++++++ 13 files changed, 994 insertions(+), 3 deletions(-) create mode 100644 docs/en/docs/img/tutorial/request-form-models/image01.png create mode 100644 docs/en/docs/tutorial/request-form-models.md create mode 100644 docs_src/request_form_models/tutorial001.py create mode 100644 docs_src/request_form_models/tutorial001_an.py create mode 100644 docs_src/request_form_models/tutorial001_an_py39.py create mode 100644 scripts/playwright/request_form_models/image01.py create mode 100644 tests/test_forms_single_model.py create mode 100644 tests/test_tutorial/test_request_form_models/__init__.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py diff --git a/docs/en/docs/img/tutorial/request-form-models/image01.png b/docs/en/docs/img/tutorial/request-form-models/image01.png new file mode 100644 index 0000000000000000000000000000000000000000..3fe32c03d589e76abec5e9c6b71374ebd4e8cd2c GIT binary patch literal 44487 zcmeFZcT|(j_b-b2Dz8{DDj*>68l^Ys(k&DL0RgF@_uhL8ib&{6RjSe3GerJ&n@emd;U6qoOQFZ);yV+XJ+p`lX>?3?7g3`_bT#tDCj82$jI&} zyp>TWBfCz#ygKyvRbugyN%0D?xZ(r=sS4^yATZ0)ghX z0GGhuk!4}GYJ%u$g6MO9t>3pz-qDliELRCcS^I8pie4O=Wek*=8TIyP`lz4jLD1fKsp$iDphv_MXSl#dKWT2O9^ z%Lx`$sAy=k!72(0wNw)9#NMG=CdYZQ zE~Mg!Zftr(!AO~sUW>G~7lmI4de6K%a^2iK*m1!|g!2jw>`3U!Qu^BTIbVs_lWm4mk{>>lazmr6t~~;<}0!)J88oGYQo}hN0Sr6 za9%D7Qs-2Fy<}8er zTQjemmqFq?-UK!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DJ&O@<0ATH4FbQe#hI5MhbD9ql-eF#=LSO zKRJ5<4c8=+)4wB5Mne^-QuO4-`~Lz+ CMaG{1 literal 0 HcmV?d00001 diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..8bb1ffb1f --- /dev/null +++ b/docs/en/docs/tutorial/request-form-models.md @@ -0,0 +1,65 @@ +# Form Models + +You can use Pydantic models to declare form fields in FastAPI. + +/// info + +To use forms, first install `python-multipart`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` + +/// + +/// note + +This is supported since FastAPI version `0.113.0`. 🤓 + +/// + +## Pydantic Models for Forms + +You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9-11 15" +{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-10 14" +{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7-9 13" +{!> ../../../docs_src/request_form_models/tutorial001.py!} +``` + +//// + +FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined. + +## Check the Docs + +You can verify it in the docs UI at `/docs`: + +
          + +
          diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 528c80b8e..7c810c2d7 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -129,6 +129,7 @@ nav: - tutorial/extra-models.md - tutorial/response-status-code.md - tutorial/request-forms.md + - tutorial/request-form-models.md - tutorial/request-files.md - tutorial/request-forms-and-files.md - tutorial/handling-errors.md diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py new file mode 100644 index 000000000..98feff0b9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py new file mode 100644 index 000000000..30483d445 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py new file mode 100644 index 000000000..7cc81aae9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an_py39.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 7ac18d941..98ce17b55 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -33,6 +33,7 @@ from fastapi._compat import ( field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, + get_model_fields, is_bytes_field, is_bytes_sequence_field, is_scalar_field, @@ -56,6 +57,7 @@ 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_model_field, get_path_param_names +from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -743,7 +745,9 @@ def _should_embed_body_fields(fields: List[ModelField]) -> bool: return True # If it's a Form (or File) field, it has to be a BaseModel to be top level # otherwise it has to be embedded, so that the key value pair can be extracted - if isinstance(first_field.field_info, params.Form): + if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( + first_field.type_, BaseModel + ): return True return False @@ -783,7 +787,8 @@ async def _extract_form_body( for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) - values[field.name] = value + if value is not None: + values[field.name] = value return values @@ -798,8 +803,14 @@ async def request_body_to_args( single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body + + fields_to_extract: List[ModelField] = body_fields + + if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_model_fields(first_field.type_) + if isinstance(received_body, FormData): - body_to_process = await _extract_form_body(body_fields, received_body) + body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py new file mode 100644 index 000000000..15bd3858c --- /dev/null +++ b/scripts/playwright/request_form_models/image01.py @@ -0,0 +1,36 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="POST /login/ Login").click() + page.get_by_role("button", name="Try it out").click() + page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py new file mode 100644 index 000000000..7ed3ba3a2 --- /dev/null +++ b/tests/test_forms_single_model.py @@ -0,0 +1,129 @@ +from typing import List, Optional + +from dirty_equals import IsDict +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormModel(BaseModel): + username: str + lastname: str + age: Optional[int] = None + tags: List[str] = ["foo", "bar"] + + +@app.post("/form/") +def post_form(user: Annotated[FormModel, Form()]): + return user + + +client = TestClient(app) + + +def test_send_all_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "70", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": 70, + "tags": ["plumbus", "citadel"], + } + + +def test_defaults(): + response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": None, + "tags": ["foo", "bar"], + } + + +def test_invalid_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "seventy", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "age"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "seventy", + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "age"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_no_data(): + response = client.post("/form/") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"]}, + }, + { + "type": "missing", + "loc": ["body", "lastname"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"]}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "lastname"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) diff --git a/tests/test_tutorial/test_request_form_models/__init__.py b/tests/test_tutorial/test_request_form_models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py new file mode 100644 index 000000000..46c130ee8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001 import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py new file mode 100644 index 000000000..4e14d89c8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py new file mode 100644 index 000000000..2e6426aa7 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py @@ -0,0 +1,240 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from tests.utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } From e787f854ddbe12d08ae6b13298b6d5eda7e20928 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 15:17:13 +0000 Subject: [PATCH 217/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9b44bc9a8..c6cbc7658 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Features + +* ✨ Add support for Pydantic models in `Form` parameters. PR [#12129](https://github.com/fastapi/fastapi/pull/12129) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.4 This release is mainly a big internal refactor to enable adding support for Pydantic models for `Form` fields, but that feature comes in the next release. From afdda4e50ba002c951233f5bedcc64068d59d212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:21:35 +0200 Subject: [PATCH 218/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20Coh?= =?UTF-8?q?erence=20link=20(#12130)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/docs/deployment/cloud.md | 2 +- docs/en/overrides/main.html | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5554f71d4..3b01b713a 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The key features are: - + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 3a767b6b1..d96646fb3 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -17,7 +17,7 @@ gold: - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs + - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=website title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index 3ea5087f8..41ada859d 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,4 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Coherence +* Coherence diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 47e46c4bf..463c5af3b 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -59,7 +59,7 @@
          - + From 179f838c366b1d9ac74e114949c5c6cfe713ec03 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 5 Sep 2024 15:23:05 +0000 Subject: [PATCH 219/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c6cbc7658..acf53e3de 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✨ Add support for Pydantic models in `Form` parameters. PR [#12129](https://github.com/fastapi/fastapi/pull/12129) by [@tiangolo](https://github.com/tiangolo). +### Internal + +* 🔧 Update sponsors: Coherence link. PR [#12130](https://github.com/fastapi/fastapi/pull/12130) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.4 This release is mainly a big internal refactor to enable adding support for Pydantic models for `Form` fields, but that feature comes in the next release. From d86f6603029def91e0798ca42f5fd12eff13c87b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 5 Sep 2024 17:25:29 +0200 Subject: [PATCH 220/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?3.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 25 +++++++++++++++++++++++++ fastapi/__init__.py | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index acf53e3de..0571523bf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,31 @@ hide: ## Latest Changes +## 0.113.0 + +Now you can declare form fields with Pydantic models: + +```python +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data +``` + +Read the new docs: [Form Models](https://fastapi.tiangolo.com/tutorial/request-form-models/). + ### Features * ✨ Add support for Pydantic models in `Form` parameters. PR [#12129](https://github.com/fastapi/fastapi/pull/12129) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 1e10bf557..f785f81cd 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.112.4" +__version__ = "0.113.0" from starlette import status as status From c411b81c29f0e8365e0710baf951b4a42039a2e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 6 Sep 2024 17:57:43 +0200 Subject: [PATCH 221/356] =?UTF-8?q?=E2=9C=85=20Update=20internal=20tests?= =?UTF-8?q?=20for=20latest=20Pydantic,=20including=20CI=20tweaks=20to=20in?= =?UTF-8?q?stall=20the=20latest=20Pydantic=20(#12147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 4 ++-- tests/test_openapi_examples.py | 27 ++++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e9db49b51..fb4b083c4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -37,7 +37,7 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' run: pip install -r requirements-tests.txt - name: Install Pydantic v2 - run: pip install "pydantic>=2.0.2,<3.0.0" + run: pip install --upgrade "pydantic>=2.0.2,<3.0.0" - name: Lint run: bash scripts/lint.sh @@ -79,7 +79,7 @@ jobs: run: pip install "pydantic>=1.10.0,<2.0.0" - name: Install Pydantic v2 if: matrix.pydantic-version == 'pydantic-v2' - run: pip install "pydantic>=2.0.2,<3.0.0" + run: pip install --upgrade "pydantic>=2.0.2,<3.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py index 6597e5058..b3f83ae23 100644 --- a/tests/test_openapi_examples.py +++ b/tests/test_openapi_examples.py @@ -155,13 +155,26 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "allOf": [{"$ref": "#/components/schemas/Item"}], - "title": "Item", - "examples": [ - {"data": "Data in Body examples, example1"} - ], - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ) + | IsDict( + { + # TODO: remove when deprecating Pydantic v1 + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ), "examples": { "Example One": { "summary": "Example One Summary", From 1b06b532677c91006efe01e4bd09b5d91f5df261 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 6 Sep 2024 15:58:05 +0000 Subject: [PATCH 222/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0571523bf..2b9bd3e87 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ✅ Update internal tests for latest Pydantic, including CI tweaks to install the latest Pydantic. PR [#12147](https://github.com/fastapi/fastapi/pull/12147) by [@tiangolo](https://github.com/tiangolo). + ## 0.113.0 Now you can declare form fields with Pydantic models: From 4633b1bca933e68dac5c3bcce797ff5963debe2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 6 Sep 2024 19:31:18 +0200 Subject: [PATCH 223/356] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20forbi?= =?UTF-8?q?dding=20extra=20form=20fields=20with=20Pydantic=20models=20(#12?= =?UTF-8?q?134)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- docs/en/docs/tutorial/request-form-models.md | 75 ++++++- docs_src/request_form_models/tutorial002.py | 15 ++ .../request_form_models/tutorial002_an.py | 16 ++ .../tutorial002_an_py39.py | 17 ++ .../request_form_models/tutorial002_pv1.py | 17 ++ .../request_form_models/tutorial002_pv1_an.py | 18 ++ .../tutorial002_pv1_an_py39.py | 19 ++ fastapi/dependencies/utils.py | 3 + .../test_tutorial002.py | 196 +++++++++++++++++ .../test_tutorial002_an.py | 196 +++++++++++++++++ .../test_tutorial002_an_py39.py | 203 ++++++++++++++++++ .../test_tutorial002_pv1.py | 189 ++++++++++++++++ .../test_tutorial002_pv1_an.py | 196 +++++++++++++++++ .../test_tutorial002_pv1_an_p39.py | 203 ++++++++++++++++++ 14 files changed, 1360 insertions(+), 3 deletions(-) create mode 100644 docs_src/request_form_models/tutorial002.py create mode 100644 docs_src/request_form_models/tutorial002_an.py create mode 100644 docs_src/request_form_models/tutorial002_an_py39.py create mode 100644 docs_src/request_form_models/tutorial002_pv1.py create mode 100644 docs_src/request_form_models/tutorial002_pv1_an.py create mode 100644 docs_src/request_form_models/tutorial002_pv1_an_py39.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py create mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index 8bb1ffb1f..a317ee14d 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -1,6 +1,6 @@ # Form Models -You can use Pydantic models to declare form fields in FastAPI. +You can use **Pydantic models** to declare **form fields** in FastAPI. /// info @@ -22,7 +22,7 @@ This is supported since FastAPI version `0.113.0`. 🤓 ## Pydantic Models for Forms -You just need to declare a Pydantic model with the fields you want to receive as form fields, and then declare the parameter as `Form`: +You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`: //// tab | Python 3.9+ @@ -54,7 +54,7 @@ Prefer to use the `Annotated` version if possible. //// -FastAPI will extract the data for each field from the form data in the request and give you the Pydantic model you defined. +**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined. ## Check the Docs @@ -63,3 +63,72 @@ You can verify it in the docs UI at `/docs`:
          + +## Restrict Extra Form Fields + +In some special use cases (probably not very common), you might want to **restrict** the form fields to only those declared in the Pydantic model. And **forbid** any **extra** fields. + +/// note + +This is supported since FastAPI version `0.114.0`. 🤓 + +/// + +You can use Pydantic's model configuration to `forbid` any `extra` fields: + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/request_form_models/tutorial002.py!} +``` + +//// + +If a client tries to send some extra data, they will receive an **error** response. + +For example, if the client tries to send the form fields: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +They will receive an error response telling them that the field `extra` is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Summary + +You can use Pydantic models to declare form fields in FastAPI. 😎 diff --git a/docs_src/request_form_models/tutorial002.py b/docs_src/request_form_models/tutorial002.py new file mode 100644 index 000000000..59b329e8d --- /dev/null +++ b/docs_src/request_form_models/tutorial002.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_an.py b/docs_src/request_form_models/tutorial002_an.py new file mode 100644 index 000000000..bcb022795 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an.py @@ -0,0 +1,16 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_an_py39.py b/docs_src/request_form_models/tutorial002_an_py39.py new file mode 100644 index 000000000..3004e0852 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1.py b/docs_src/request_form_models/tutorial002_pv1.py new file mode 100644 index 000000000..d5f7db2a6 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an.py b/docs_src/request_form_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..fe9dbc344 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an.py @@ -0,0 +1,18 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an_py39.py b/docs_src/request_form_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..942d5d411 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 98ce17b55..6083b7319 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -789,6 +789,9 @@ async def _extract_form_body( value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value + for key, value in received_body.items(): + if key not in values: + values[key] = value return values diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py new file mode 100644 index 000000000..76f480001 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002 import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py new file mode 100644 index 000000000..179b2977d --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_an import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py new file mode 100644 index 000000000..510ad9d7c --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py @@ -0,0 +1,203 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_py39, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_an_py39 import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py new file mode 100644 index 000000000..249b9379d --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py @@ -0,0 +1,189 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1 import app + + client = TestClient(app) + return client + + +@needs_pydanticv1 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv1 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +@needs_pydanticv1 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py new file mode 100644 index 000000000..44cb3c32b --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1_an import app + + client = TestClient(app) + return client + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py new file mode 100644 index 000000000..899549e40 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py @@ -0,0 +1,203 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_py39, needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1_an_py39 import app + + client = TestClient(app) + return client + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } From a11e392f5f0ae8b50f92252f811764d48929466f Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 6 Sep 2024 17:31:44 +0000 Subject: [PATCH 224/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2b9bd3e87..7f4353cfe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Features + +* ✨ Add support for forbidding extra form fields with Pydantic models. PR [#12134](https://github.com/fastapi/fastapi/pull/12134) by [@tiangolo](https://github.com/tiangolo). + ### Internal * ✅ Update internal tests for latest Pydantic, including CI tweaks to install the latest Pydantic. PR [#12147](https://github.com/fastapi/fastapi/pull/12147) by [@tiangolo](https://github.com/tiangolo). From 4ff22a0c4167e5fe5dc039b29531329398d67ad5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 6 Sep 2024 19:38:23 +0200 Subject: [PATCH 225/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs,=20Form=20?= =?UTF-8?q?Models=20section=20title,=20to=20match=20config=20name=20(#1215?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/request-form-models.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index a317ee14d..1440d17b8 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -64,7 +64,7 @@ You can verify it in the docs UI at `/docs`:
          -## Restrict Extra Form Fields +## Forbid Extra Form Fields In some special use cases (probably not very common), you might want to **restrict** the form fields to only those declared in the Pydantic model. And **forbid** any **extra** fields. From e68d8c60fbe22609b6e3c3a652474088eeba18e6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 6 Sep 2024 17:38:50 +0000 Subject: [PATCH 226/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7f4353cfe..b7db0f780 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✨ Add support for forbidding extra form fields with Pydantic models. PR [#12134](https://github.com/fastapi/fastapi/pull/12134) by [@tiangolo](https://github.com/tiangolo). +### Docs + +* 📝 Update docs, Form Models section title, to match config name. PR [#12152](https://github.com/fastapi/fastapi/pull/12152) by [@tiangolo](https://github.com/tiangolo). + ### Internal * ✅ Update internal tests for latest Pydantic, including CI tweaks to install the latest Pydantic. PR [#12147](https://github.com/fastapi/fastapi/pull/12147) by [@tiangolo](https://github.com/tiangolo). From 74842f0a604f9e90e6ffb71c352186389060b1b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 6 Sep 2024 19:40:27 +0200 Subject: [PATCH 227/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b7db0f780..94f494375 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,30 @@ hide: ## Latest Changes +You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's `model_config = {"extra": "forbid"}`: + +```python +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data +``` + +Read the new docs: [Form Models - Forbid Extra Form Fields](https://fastapi.tiangolo.com/tutorial/request-form-models/#forbid-extra-form-fields). + ### Features * ✨ Add support for forbidding extra form fields with Pydantic models. PR [#12134](https://github.com/fastapi/fastapi/pull/12134) by [@tiangolo](https://github.com/tiangolo). From bde12faea20313e4570f7cb896c201058c26e546 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 6 Sep 2024 19:41:13 +0200 Subject: [PATCH 228/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?4.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 94f494375..557498278 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.114.0 + You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's `model_config = {"extra": "forbid"}`: ```python diff --git a/fastapi/__init__.py b/fastapi/__init__.py index f785f81cd..dce17360f 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.113.0" +__version__ = "0.114.0" from starlette import status as status From b60d36e7533e0ae299cdff0d72b078d1f036ac67 Mon Sep 17 00:00:00 2001 From: Vaibhav <35167042+surreal30@users.noreply.github.com> Date: Fri, 6 Sep 2024 23:36:20 +0530 Subject: [PATCH 229/356] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/params.py`=20(#12143)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/params.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/params.py b/fastapi/params.py index 3dfa5a1a3..90ca7cb01 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -556,7 +556,7 @@ class Body(FieldInfo): kwargs["examples"] = examples if regex is not None: warnings.warn( - "`regex` has been depreacated, please use `pattern` instead", + "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) From 4b9e5b3a7433f13dcb1ca6d284326b1753231af2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 6 Sep 2024 18:06:45 +0000 Subject: [PATCH 230/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 557498278..23bb2d9d1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30). + ## 0.114.0 You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's `model_config = {"extra": "forbid"}`: From edb584199f3341b205da5d7e1686c54d8719b82d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 7 Sep 2024 17:21:14 +0200 Subject: [PATCH 231/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20`issue-manager.?= =?UTF-8?q?yml`=20(#12159)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue-manager.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index d5b947a9c..fbb856792 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -2,7 +2,7 @@ name: Issue Manager on: schedule: - - cron: "10 3 * * *" + - cron: "13 22 * * *" issue_comment: types: - created @@ -16,6 +16,7 @@ on: permissions: issues: write + pull-requests: write jobs: issue-manager: @@ -35,8 +36,8 @@ jobs: "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." }, - "changes-requested": { + "waiting": { "delay": 2628000, - "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." + "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." } } From b501fc6dafbef19a9d17b8484469ca81426c8e9d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 7 Sep 2024 15:24:06 +0000 Subject: [PATCH 232/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 23bb2d9d1..16bd6e526 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30). ## 0.114.0 From ec2a50829202ab98f166f581053d82b74d3f1130 Mon Sep 17 00:00:00 2001 From: BORA <88664069+BORA040126@users.noreply.github.com> Date: Sun, 8 Sep 2024 08:35:43 +0900 Subject: [PATCH 233/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/project-generation.md`=20(#12157)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/project-generation.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 docs/ko/docs/project-generation.md diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md new file mode 100644 index 000000000..019919f77 --- /dev/null +++ b/docs/ko/docs/project-generation.md @@ -0,0 +1,28 @@ +# Full Stack FastAPI 템플릿 + +템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁 + +많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 (프로젝트를) 시작하는 데 사용할 수 있습니다. + +GitHub 저장소: Full Stack FastAPI 템플릿 + +## Full Stack FastAPI 템플릿 - 기술 스택과 기능들 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com): Python 백엔드 API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com): Python SQL 데이터 상호작용을 위한 (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev): FastAPI에 의해 사용되는, 데이터 검증과 설정관리. + - 💾 [PostgreSQL](https://www.postgresql.org): SQL 데이터베이스. +- 🚀 [React](https://react.dev): 프론트엔드. + - 💃 TypeScript, hooks, Vite 및 기타 현대적인 프론트엔드 스택을 사용. + - 🎨 [Chakra UI](https://chakra-ui.com): 프론트엔드 컴포넌트. + - 🤖 자동으로 생성된 프론트엔드 클라이언트. + - 🧪 E2E 테스트를 위한 Playwright. + - 🦇 다크 모드 지원. +- 🐋 [Docker Compose](https://www.docker.com): 개발 환경과 프로덕션(운영). +- 🔒 기본으로 지원되는 안전한 비밀번호 해싱. +- 🔑 JWT 토큰 인증. +- 📫 이메일 기반 비밀번호 복구. +- ✅ [Pytest]를 이용한 테스트(https://pytest.org). +- 📞 [Traefik](https://traefik.io): 리버스 프록시 / 로드 밸런서. +- 🚢 Docker Compose를 이용한 배포 지침: 자동 HTTPS 인증서를 처리하기 위한 프론트엔드 Traefik 프록시 설정 방법을 포함. +- 🏭 GitHub Actions를 기반으로 CI (지속적인 통합) 및 CD (지속적인 배포). From 3a4431b6feb50a86a60ce034580cf9fbacee9d32 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 7 Sep 2024 23:36:05 +0000 Subject: [PATCH 234/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 16bd6e526..e09eb57b6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126). + ### Internal * 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo). From 270aef71c47694ca349afeba95d13ade195185d2 Mon Sep 17 00:00:00 2001 From: Guillaume Fassot <97948781+prometek@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:36:53 +0200 Subject: [PATCH 235/356] =?UTF-8?q?=F0=9F=93=9D=20Remove=20duplicate=20lin?= =?UTF-8?q?e=20in=20docs=20for=20`docs/en/docs/environment-variables.md`?= =?UTF-8?q?=20(#12169)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/environment-variables.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md index 78e82d5af..43dd06add 100644 --- a/docs/en/docs/environment-variables.md +++ b/docs/en/docs/environment-variables.md @@ -243,8 +243,6 @@ This way, when you type `python` in the terminal, the system will find the Pytho //// -This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. - So, if you type:
          From c49c4e7df8eef1ab4ed5baacdf02df3a10aaaae1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 8 Sep 2024 20:37:14 +0000 Subject: [PATCH 236/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e09eb57b6..6e84911e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Remove duplicate line in docs for `docs/en/docs/environment-variables.md`. PR [#12169](https://github.com/fastapi/fastapi/pull/12169) by [@prometek](https://github.com/prometek). + ### Translations * 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126). From a67167dce3f3b33ef1789c0eeb7a2dcdf2cc4314 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 20:35:50 +0200 Subject: [PATCH 237/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12176)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ⬆ [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.3 → v0.6.4](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.3...v0.6.4) * bump ruff in tests requirements as well --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg --- .pre-commit-config.yaml | 2 +- requirements-tests.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7e58afd4b..f74816f12 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.3 + rev: v0.6.4 hooks: - id: ruff args: diff --git a/requirements-tests.txt b/requirements-tests.txt index de5fdb8a2..809a19c0c 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.6.3 +ruff ==0.6.4 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel From da4670cf775ff7c2ef98b7157a71a91fe980816e Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Sep 2024 18:36:15 +0000 Subject: [PATCH 238/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6e84911e9..3af1a5ade 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12176](https://github.com/fastapi/fastapi/pull/12176) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30). From fc601bcb4b2dd97e3c7918c8f59f97a62df06abc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Sep 2024 11:07:46 +0200 Subject: [PATCH 239/356] =?UTF-8?q?=E2=AC=86=20Bump=20tiangolo/issue-manag?= =?UTF-8?q?er=20from=200.5.0=20to=200.5.1=20(#12173)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [tiangolo/issue-manager](https://github.com/tiangolo/issue-manager) from 0.5.0 to 0.5.1. - [Release notes](https://github.com/tiangolo/issue-manager/releases) - [Commits](https://github.com/tiangolo/issue-manager/compare/0.5.0...0.5.1) --- updated-dependencies: - dependency-name: tiangolo/issue-manager dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/issue-manager.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index fbb856792..439084434 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -27,7 +27,7 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: tiangolo/issue-manager@0.5.0 + - uses: tiangolo/issue-manager@0.5.1 with: token: ${{ secrets.GITHUB_TOKEN }} config: > From bc715d55bc1ee3aedf4d429ca4e08ae39e0bbb90 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Sep 2024 09:08:09 +0000 Subject: [PATCH 240/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3af1a5ade..b9eaed65d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Internal +* ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1. PR [#12173](https://github.com/fastapi/fastapi/pull/12173) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12176](https://github.com/fastapi/fastapi/pull/12176) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30). From 80e2cd12747df2de38b4ab3ee1ee1cb889ee242b Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Tue, 10 Sep 2024 07:34:25 -0300 Subject: [PATCH 241/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/debugging.md`=20(#12165)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/debugging.md | 115 +++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 docs/pt/docs/tutorial/debugging.md diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md new file mode 100644 index 000000000..54582fcbc --- /dev/null +++ b/docs/pt/docs/tutorial/debugging.md @@ -0,0 +1,115 @@ +# Depuração + +Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Code ou PyCharm. + +## Chamar `uvicorn` + +Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: + +```Python hl_lines="1 15" +{!../../../docs_src/debugging/tutorial001.py!} +``` + +### Sobre `__name__ == "__main__"` + +O objetivo principal de `__name__ == "__main__"` é ter algum código que seja executado quando seu arquivo for chamado com: + +
          + +```console +$ python myapp.py +``` + +
          + +mas não é chamado quando outro arquivo o importa, como em: + +```Python +from myapp import app +``` + +#### Mais detalhes + +Digamos que seu arquivo se chama `myapp.py`. + +Se você executá-lo com: + +
          + +```console +$ python myapp.py +``` + +
          + +então a variável interna `__name__` no seu arquivo, criada automaticamente pelo Python, terá como valor a string `"__main__"`. + +Então, a seção: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +vai executar. + +--- + +Isso não acontecerá se você importar esse módulo (arquivo). + +Então, se você tiver outro arquivo `importer.py` com: + +```Python +from myapp import app + +# Mais um pouco de código +``` + +nesse caso, a variável criada automaticamente dentro de `myapp.py` não terá a variável `__name__` com o valor `"__main__"`. + +Então, a linha: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +não será executada. + +/// info | "Informação" + +Para mais informações, consulte a documentação oficial do Python. + +/// + +## Execute seu código com seu depurador + +Como você está executando o servidor Uvicorn diretamente do seu código, você pode chamar seu programa Python (seu aplicativo FastAPI) diretamente do depurador. + +--- + +Por exemplo, no Visual Studio Code, você pode: + +* Ir para o painel "Debug". +* "Add configuration...". +* Selecionar "Python" +* Executar o depurador com a opção "`Python: Current File (Integrated Terminal)`". + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + + +--- + +Se você usar o Pycharm, você pode: + +* Abrir o menu "Executar". +* Selecionar a opção "Depurar...". +* Então um menu de contexto aparece. +* Selecionar o arquivo para depurar (neste caso, `main.py`). + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + From 73d4f347df83c8e59ab55c9dfdbd974351e6efc5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Sep 2024 10:34:46 +0000 Subject: [PATCH 242/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b9eaed65d..7492242a4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126). ### Internal From a4a7925045e42030528c6f1fdeaa059e811455c0 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Tue, 10 Sep 2024 07:35:14 -0300 Subject: [PATCH 243/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/testing.md`=20(#12164)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/testing.md | 249 +++++++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 docs/pt/docs/tutorial/testing.md diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md new file mode 100644 index 000000000..f734a7d9a --- /dev/null +++ b/docs/pt/docs/tutorial/testing.md @@ -0,0 +1,249 @@ +# Testando + +Graças ao Starlette, testar aplicativos **FastAPI** é fácil e agradável. + +Ele é baseado no HTTPX, que por sua vez é projetado com base em Requests, por isso é muito familiar e intuitivo. + +Com ele, você pode usar o pytest diretamente com **FastAPI**. + +## Usando `TestClient` + +/// info | "Informação" + +Para usar o `TestClient`, primeiro instale o `httpx`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +```console +$ pip install httpx +``` + +/// + +Importe `TestClient`. + +Crie um `TestClient` passando seu aplicativo **FastAPI** para ele. + +Crie funções com um nome que comece com `test_` (essa é a convenção padrão do `pytest`). + +Use o objeto `TestClient` da mesma forma que você faz com `httpx`. + +Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). + +```Python hl_lines="2 12 15-18" +{!../../../docs_src/app_testing/tutorial001.py!} +``` + +/// tip | "Dica" + +Observe que as funções de teste são `def` normais, não `async def`. + +E as chamadas para o cliente também são chamadas normais, não usando `await`. + +Isso permite que você use `pytest` diretamente sem complicações. + +/// + +/// note | "Detalhes técnicos" + +Você também pode usar `from starlette.testclient import TestClient`. + +**FastAPI** fornece o mesmo `starlette.testclient` que `fastapi.testclient` apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente da Starlette. + +/// + +/// tip | "Dica" + +Se você quiser chamar funções `async` em seus testes além de enviar solicitações ao seu aplicativo FastAPI (por exemplo, funções de banco de dados assíncronas), dê uma olhada em [Testes assíncronos](../advanced/async-tests.md){.internal-link target=_blank} no tutorial avançado. + +/// + +## Separando testes + +Em uma aplicação real, você provavelmente teria seus testes em um arquivo diferente. + +E seu aplicativo **FastAPI** também pode ser composto de vários arquivos/módulos, etc. + +### Arquivo do aplicativo **FastAPI** + +Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativos maiores](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +No arquivo `main.py` você tem seu aplicativo **FastAPI**: + + +```Python +{!../../../docs_src/app_testing/main.py!} +``` + +### Arquivo de teste + +Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia estar no mesmo pacote Python (o mesmo diretório com um arquivo `__init__.py`): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): + +```Python hl_lines="3" +{!../../../docs_src/app_testing/test_main.py!} +``` + +...e ter o código para os testes como antes. + +## Testando: exemplo estendido + +Agora vamos estender este exemplo e adicionar mais detalhes para ver como testar diferentes partes. + +### Arquivo de aplicativo **FastAPI** estendido + +Vamos continuar com a mesma estrutura de arquivo de antes: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Digamos que agora o arquivo `main.py` com seu aplicativo **FastAPI** tenha algumas outras **operações de rotas**. + +Ele tem uma operação `GET` que pode retornar um erro. + +Ele tem uma operação `POST` que pode retornar vários erros. + +Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | "Dica" + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Arquivo de teste estendido + +Você pode então atualizar `test_main.py` com os testes estendidos: + +```Python +{!> ../../../docs_src/app_testing/app_b/test_main.py!} +``` + +Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. + +Depois é só fazer o mesmo nos seus testes. + +Por exemplo: + +* Para passar um parâmetro *path* ou *query*, adicione-o à própria URL. +* Para passar um corpo JSON, passe um objeto Python (por exemplo, um `dict`) para o parâmetro `json`. +* Se você precisar enviar *Dados de Formulário* em vez de JSON, use o parâmetro `data`. +* Para passar *headers*, use um `dict` no parâmetro `headers`. +* Para *cookies*, um `dict` no parâmetro `cookies`. + +Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX. + +/// info | "Informação" + +Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic. + +Se você tiver um modelo Pydantic em seu teste e quiser enviar seus dados para o aplicativo durante o teste, poderá usar o `jsonable_encoder` descrito em [Codificador compatível com JSON](encoder.md){.internal-link target=_blank}. + +/// + +## Execute-o + +Depois disso, você só precisa instalar o `pytest`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +
          + +```console +$ pip install pytest + +---> 100% +``` + +
          + +Ele detectará os arquivos e os testes automaticamente, os executará e informará os resultados para você. + +Execute os testes com: + +
          + +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
          From e69ba263861b440fce06b55bedf83bd08646452b Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Tue, 10 Sep 2024 07:36:42 -0300 Subject: [PATCH 244/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/environment-variables.md`=20(#1216?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/environment-variables.md | 298 ++++++++++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 docs/pt/docs/environment-variables.md diff --git a/docs/pt/docs/environment-variables.md b/docs/pt/docs/environment-variables.md new file mode 100644 index 000000000..360d1c496 --- /dev/null +++ b/docs/pt/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Variáveis de Ambiente + +/// tip | "Dica" + +Se você já sabe o que são "variáveis de ambiente" e como usá-las, pode pular esta seção. + +/// + +Uma variável de ambiente (também conhecida como "**env var**") é uma variável que existe **fora** do código Python, no **sistema operacional**, e pode ser lida pelo seu código Python (ou por outros programas também). + +Variáveis de ambiente podem ser úteis para lidar com **configurações** do aplicativo, como parte da **instalação** do Python, etc. + +## Criar e Usar Variáveis de Ambiente + +Você pode **criar** e usar variáveis de ambiente no **shell (terminal)**, sem precisar do Python: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Você pode criar uma variável de ambiente MY_NAME com +$ export MY_NAME="Wade Wilson" + +// Então você pode usá-la com outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Criar uma variável de ambiente MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Usá-la com outros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +## Ler Variáveis de Ambiente no Python + +Você também pode criar variáveis de ambiente **fora** do Python, no terminal (ou com qualquer outro método) e depois **lê-las no Python**. + +Por exemplo, você poderia ter um arquivo `main.py` com: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | "Dica" + +O segundo argumento para `os.getenv()` é o valor padrão a ser retornado. + +Se não for fornecido, é `None` por padrão, Aqui fornecemos `"World"` como o valor padrão a ser usado. + +/// + +Então você poderia chamar esse programa Python: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ $Env:MY_NAME = "Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
          + +//// + +Como as variáveis de ambiente podem ser definidas fora do código, mas podem ser lidas pelo código e não precisam ser armazenadas (com versão no `git`) com o restante dos arquivos, é comum usá-las para configurações ou **definições**. + +Você também pode criar uma variável de ambiente apenas para uma **invocação específica do programa**, que só está disponível para aquele programa e apenas pela duração dele. + +Para fazer isso, crie-a na mesma linha, antes do próprio programa: + +
          + +```console +// Criar uma variável de ambiente MY_NAME para esta chamada de programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python + +// A variável de ambiente não existe mais depois +$ python main.py + +Hello World from Python +``` + +
          + +/// tip | "Dica" + +Você pode ler mais sobre isso em The Twelve-Factor App: Config. + +/// + +## Tipos e Validação + +Essas variáveis de ambiente só podem lidar com **strings de texto**, pois são externas ao Python e precisam ser compatíveis com outros programas e com o resto do sistema (e até mesmo com diferentes sistemas operacionais, como Linux, Windows, macOS). + +Isso significa que **qualquer valor** lido em Python de uma variável de ambiente **será uma `str`**, e qualquer conversão para um tipo diferente ou qualquer validação precisa ser feita no código. + +Você aprenderá mais sobre como usar variáveis de ambiente para lidar com **configurações do aplicativo** no [Guia do Usuário Avançado - Configurações e Variáveis de Ambiente](./advanced/settings.md){.internal-link target=_blank}. + +## Variável de Ambiente `PATH` + +Existe uma variável de ambiente **especial** chamada **`PATH`** que é usada pelos sistemas operacionais (Linux, macOS, Windows) para encontrar programas para executar. + +O valor da variável `PATH` é uma longa string composta por diretórios separados por dois pontos `:` no Linux e macOS, e por ponto e vírgula `;` no Windows. + +Por exemplo, a variável de ambiente `PATH` poderia ter esta aparência: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Quando você digita um **comando** no terminal, o sistema operacional **procura** o programa em **cada um dos diretórios** listados na variável de ambiente `PATH`. + +Por exemplo, quando você digita `python` no terminal, o sistema operacional procura um programa chamado `python` no **primeiro diretório** dessa lista. + +Se ele o encontrar, então ele o **usará**. Caso contrário, ele continua procurando nos **outros diretórios**. + +### Instalando o Python e Atualizando o `PATH` + +Durante a instalação do Python, você pode ser questionado sobre a atualização da variável de ambiente `PATH`. + +//// tab | Linux, macOS + +Vamos supor que você instale o Python e ele fique em um diretório `/opt/custompython/bin`. + +Se você concordar em atualizar a variável de ambiente `PATH`, o instalador adicionará `/opt/custompython/bin` para a variável de ambiente `PATH`. + +Poderia parecer assim: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Dessa forma, ao digitar `python` no terminal, o sistema encontrará o programa Python em `/opt/custompython/bin` (último diretório) e o utilizará. + +//// + +//// tab | Windows + +Digamos que você instala o Python e ele acaba em um diretório `C:\opt\custompython\bin`. + +Se você disser sim para atualizar a variável de ambiente `PATH`, o instalador adicionará `C:\opt\custompython\bin` à variável de ambiente `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Dessa forma, quando você digitar `python` no terminal, o sistema encontrará o programa Python em `C:\opt\custompython\bin` (o último diretório) e o utilizará. + +//// + +Então, se você digitar: + +
          + +```console +$ python +``` + +
          + +//// tab | Linux, macOS + +O sistema **encontrará** o programa `python` em `/opt/custompython/bin` e o executará. + +Seria aproximadamente equivalente a digitar: + +
          + +```console +$ /opt/custompython/bin/python +``` + +
          + +//// + +//// tab | Windows + +O sistema **encontrará** o programa `python` em `C:\opt\custompython\bin\python` e o executará. + +Seria aproximadamente equivalente a digitar: + +
          + +```console +$ C:\opt\custompython\bin\python +``` + +
          + +//// + +Essas informações serão úteis ao aprender sobre [Ambientes Virtuais](virtual-environments.md){.internal-link target=_blank}. + +## Conclusão + +Com isso, você deve ter uma compreensão básica do que são **variáveis ​​de ambiente** e como usá-las em Python. + +Você também pode ler mais sobre elas na Wikipedia para Variáveis ​​de Ambiente. + +Em muitos casos, não é muito óbvio como as variáveis ​​de ambiente seriam úteis e aplicáveis ​​imediatamente. Mas elas continuam aparecendo em muitos cenários diferentes quando você está desenvolvendo, então é bom saber sobre elas. + +Por exemplo, você precisará dessas informações na próxima seção, sobre [Ambientes Virtuais](virtual-environments.md). From 944b6e507e326f986061e99936c80aa565da669f Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Tue, 10 Sep 2024 07:37:13 -0300 Subject: [PATCH 245/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/virtual-environments.md`=20(#12163?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/virtual-environments.md | 844 +++++++++++++++++++++++++++ 1 file changed, 844 insertions(+) create mode 100644 docs/pt/docs/virtual-environments.md diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md new file mode 100644 index 000000000..863c8d65e --- /dev/null +++ b/docs/pt/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Ambientes Virtuais + +Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto. + +/// info | "Informação" + +Se você já sabe sobre ambientes virtuais, como criá-los e usá-los, talvez seja melhor pular esta seção. 🤓 + +/// + +/// tip | "Dica" + +Um **ambiente virtual** é diferente de uma **variável de ambiente**. + +Uma **variável de ambiente** é uma variável no sistema que pode ser usada por programas. + +Um **ambiente virtual** é um diretório com alguns arquivos. + +/// + +/// info | "Informação" + +Esta página lhe ensinará como usar **ambientes virtuais** e como eles funcionam. + +Se você estiver pronto para adotar uma **ferramenta que gerencia tudo** para você (incluindo a instalação do Python), experimente uv. + +/// + +## Criar um Projeto + +Primeiro, crie um diretório para seu projeto. + +O que normalmente faço é criar um diretório chamado `code` dentro do meu diretório home/user. + +E dentro disso eu crio um diretório por projeto. + +
          + +```console +// Vá para o diretório inicial +$ cd +// Crie um diretório para todos os seus projetos de código +$ mkdir code +// Entre nesse diretório de código +$ cd code +// Crie um diretório para este projeto +$ mkdir awesome-project +// Entre no diretório do projeto +$ cd awesome-project +``` + +
          + +## Crie um ambiente virtual + +Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**. + +/// tip | "Dica" + +Você só precisa fazer isso **uma vez por projeto**, não toda vez que trabalhar. + +/// + +//// tab | `venv` + +Para criar um ambiente virtual, você pode usar o módulo `venv` que vem com o Python. + +
          + +```console +$ python -m venv .venv +``` + +
          + +/// details | O que esse comando significa + +* `python`: usa o programa chamado `python` +* `-m`: chama um módulo como um script, nós diremos a ele qual módulo vem em seguida +* `venv`: usa o módulo chamado `venv` que normalmente vem instalado com o Python +* `.venv`: cria o ambiente virtual no novo diretório `.venv` + +/// + +//// + +//// tab | `uv` + +Se você tiver o `uv` instalado, poderá usá-lo para criar um ambiente virtual. + +
          + +```console +$ uv venv +``` + +
          + +/// tip | "Dica" + +Por padrão, `uv` criará um ambiente virtual em um diretório chamado `.venv`. + +Mas você pode personalizá-lo passando um argumento adicional com o nome do diretório. + +/// + +//// + +Esse comando cria um novo ambiente virtual em um diretório chamado `.venv`. + +/// details | `.venv` ou outro nome + +Você pode criar o ambiente virtual em um diretório diferente, mas há uma convenção para chamá-lo de `.venv`. + +/// + +## Ative o ambiente virtual + +Ative o novo ambiente virtual para que qualquer comando Python que você executar ou pacote que você instalar o utilize. + +/// tip | "Dica" + +Faça isso **toda vez** que iniciar uma **nova sessão de terminal** para trabalhar no projeto. + +/// + +//// tab | Linux, macOS + +
          + +```console +$ source .venv/bin/activate +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
          + +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
          + +```console +$ source .venv/Scripts/activate +``` + +
          + +//// + +/// tip | "Dica" + +Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente. + +Isso garante que, se você usar um **programa de terminal (CLI)** instalado por esse pacote, você usará aquele do seu ambiente virtual e não qualquer outro que possa ser instalado globalmente, provavelmente com uma versão diferente do que você precisa. + +/// + +## Verifique se o ambiente virtual está ativo + +Verifique se o ambiente virtual está ativo (o comando anterior funcionou). + +/// tip | "Dica" + +Isso é **opcional**, mas é uma boa maneira de **verificar** se tudo está funcionando conforme o esperado e se você está usando o ambiente virtual pretendido. + +/// + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
          + +Se ele mostrar o binário `python` em `.venv/bin/python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
          + +Se ele mostrar o binário `python` em `.venv\Scripts\python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +## Atualizar `pip` + +/// tip | "Dica" + +Se você usar `uv`, você o usará para instalar coisas em vez do `pip`, então não precisará atualizar o `pip`. 😎 + +/// + +Se você estiver usando `pip` para instalar pacotes (ele vem por padrão com o Python), você deve **atualizá-lo** para a versão mais recente. + +Muitos erros exóticos durante a instalação de um pacote são resolvidos apenas atualizando o `pip` primeiro. + +/// tip | "Dica" + +Normalmente, você faria isso **uma vez**, logo após criar o ambiente virtual. + +/// + +Certifique-se de que o ambiente virtual esteja ativo (com o comando acima) e execute: + +
          + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
          + +## Adicionar `.gitignore` + +Se você estiver usando **Git** (você deveria), adicione um arquivo `.gitignore` para excluir tudo em seu `.venv` do Git. + +/// tip | "Dica" + +Se você usou `uv` para criar o ambiente virtual, ele já fez isso para você, você pode pular esta etapa. 😎 + +/// + +/// tip | "Dica" + +Faça isso **uma vez**, logo após criar o ambiente virtual. + +/// + +
          + +```console +$ echo "*" > .venv/.gitignore +``` + +
          + +/// details | O que esse comando significa + +* `echo "*"`: irá "imprimir" o texto `*` no terminal (a próxima parte muda isso um pouco) +* `>`: qualquer coisa impressa no terminal pelo comando à esquerda de `>` não deve ser impressa, mas sim escrita no arquivo que vai à direita de `>` +* `.gitignore`: o nome do arquivo onde o texto deve ser escrito + +E `*` para Git significa "tudo". Então, ele ignorará tudo no diretório `.venv`. + +Esse comando criará um arquivo `.gitignore` com o conteúdo: + +```gitignore +* +``` + +/// + +## Instalar Pacotes + +Após ativar o ambiente, você pode instalar pacotes nele. + +/// tip | "Dica" + +Faça isso **uma vez** ao instalar ou atualizar os pacotes que seu projeto precisa. + +Se precisar atualizar uma versão ou adicionar um novo pacote, você **fará isso novamente**. + +/// + +### Instalar pacotes diretamente + +Se estiver com pressa e não quiser usar um arquivo para declarar os requisitos de pacote do seu projeto, você pode instalá-los diretamente. + +/// tip | "Dica" + +É uma (muito) boa ideia colocar os pacotes e versões que seu programa precisa em um arquivo (por exemplo `requirements.txt` ou `pyproject.toml`). + +/// + +//// tab | `pip` + +
          + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
          + +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
          + +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
          + +//// + +### Instalar a partir de `requirements.txt` + +Se você tiver um `requirements.txt`, agora poderá usá-lo para instalar seus pacotes. + +//// tab | `pip` + +
          + +```console +$ pip install -r requirements.txt +---> 100% +``` + +
          + +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
          + +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
          + +//// + +/// details | `requirements.txt` + +Um `requirements.txt` com alguns pacotes poderia se parecer com: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Execute seu programa + +Depois de ativar o ambiente virtual, você pode executar seu programa, e ele usará o Python dentro do seu ambiente virtual com os pacotes que você instalou lá. + +
          + +```console +$ python main.py + +Hello World +``` + +
          + +## Configure seu editor + +Você provavelmente usaria um editor. Certifique-se de configurá-lo para usar o mesmo ambiente virtual que você criou (ele provavelmente o detectará automaticamente) para que você possa obter erros de preenchimento automático e em linha. + +Por exemplo: + +* VS Code +* PyCharm + +/// tip | "Dica" + +Normalmente, você só precisa fazer isso **uma vez**, ao criar o ambiente virtual. + +/// + +## Desativar o ambiente virtual + +Quando terminar de trabalhar no seu projeto, você pode **desativar** o ambiente virtual. + +
          + +```console +$ deactivate +``` + +
          + +Dessa forma, quando você executar `python`, ele não tentará executá-lo naquele ambiente virtual com os pacotes instalados nele. + +## Pronto para trabalhar + +Agora você está pronto para começar a trabalhar no seu projeto. + + + +/// tip | "Dica" + +Você quer entender o que é tudo isso acima? + +Continue lendo. 👇🤓 + +/// + +## Por que ambientes virtuais + +Para trabalhar com o FastAPI, você precisa instalar o Python. + +Depois disso, você precisará **instalar** o FastAPI e quaisquer outros **pacotes** que queira usar. + +Para instalar pacotes, você normalmente usaria o comando `pip` que vem com o Python (ou alternativas semelhantes). + +No entanto, se você usar `pip` diretamente, os pacotes serão instalados no seu **ambiente Python global** (a instalação global do Python). + +### O Problema + +Então, qual é o problema em instalar pacotes no ambiente global do Python? + +Em algum momento, você provavelmente acabará escrevendo muitos programas diferentes que dependem de **pacotes diferentes**. E alguns desses projetos em que você trabalha dependerão de **versões diferentes** do mesmo pacote. 😱 + +Por exemplo, você pode criar um projeto chamado `philosophers-stone`, este programa depende de outro pacote chamado **`harry`, usando a versão `1`**. Então, você precisa instalar `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Então, em algum momento depois, você cria outro projeto chamado `prisoner-of-azkaban`, e esse projeto também depende de `harry`, mas esse projeto precisa do **`harry` versão `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Mas agora o problema é que, se você instalar os pacotes globalmente (no ambiente global) em vez de em um **ambiente virtual** local, você terá que escolher qual versão do `harry` instalar. + +Se você quiser executar `philosophers-stone`, precisará primeiro instalar `harry` versão `1`, por exemplo com: + +
          + +```console +$ pip install "harry==1" +``` + +
          + +E então você acabaria com `harry` versão `1` instalado em seu ambiente Python global. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Mas se você quiser executar `prisoner-of-azkaban`, você precisará desinstalar `harry` versão `1` e instalar `harry` versão `3` (ou apenas instalar a versão `3` desinstalaria automaticamente a versão `1`). + +
          + +```console +$ pip install "harry==3" +``` + +
          + +E então você acabaria com `harry` versão `3` instalado em seu ambiente Python global. + +E se você tentar executar `philosophers-stone` novamente, há uma chance de que **não funcione** porque ele precisa de `harry` versão `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | "Dica" + +É muito comum em pacotes Python tentar ao máximo **evitar alterações drásticas** em **novas versões**, mas é melhor prevenir do que remediar e instalar versões mais recentes intencionalmente e, quando possível, executar os testes para verificar se tudo está funcionando corretamente. + +/// + +Agora, imagine isso com **muitos** outros **pacotes** dos quais todos os seus **projetos dependem**. Isso é muito difícil de gerenciar. E você provavelmente acabaria executando alguns projetos com algumas **versões incompatíveis** dos pacotes, e não saberia por que algo não está funcionando. + +Além disso, dependendo do seu sistema operacional (por exemplo, Linux, Windows, macOS), ele pode ter vindo com o Python já instalado. E, nesse caso, provavelmente tinha alguns pacotes pré-instalados com algumas versões específicas **necessárias para o seu sistema**. Se você instalar pacotes no ambiente global do Python, poderá acabar **quebrando** alguns dos programas que vieram com seu sistema operacional. + +## Onde os pacotes são instalados + +Quando você instala o Python, ele cria alguns diretórios com alguns arquivos no seu computador. + +Alguns desses diretórios são os responsáveis ​​por ter todos os pacotes que você instala. + +Quando você executa: + +
          + +```console +// Não execute isso agora, é apenas um exemplo 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
          + +Isso fará o download de um arquivo compactado com o código FastAPI, normalmente do PyPI. + +Ele também fará o **download** de arquivos para outros pacotes dos quais o FastAPI depende. + +Em seguida, ele **extrairá** todos esses arquivos e os colocará em um diretório no seu computador. + +Por padrão, ele colocará os arquivos baixados e extraídos no diretório que vem com a instalação do Python, que é o **ambiente global**. + +## O que são ambientes virtuais + +A solução para os problemas de ter todos os pacotes no ambiente global é usar um **ambiente virtual para cada projeto** em que você trabalha. + +Um ambiente virtual é um **diretório**, muito semelhante ao global, onde você pode instalar os pacotes para um projeto. + +Dessa forma, cada projeto terá seu próprio ambiente virtual (diretório `.venv`) com seus próprios pacotes. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## O que significa ativar um ambiente virtual + +Quando você ativa um ambiente virtual, por exemplo com: + +//// tab | Linux, macOS + +
          + +```console +$ source .venv/bin/activate +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
          + +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
          + +```console +$ source .venv/Scripts/activate +``` + +
          + +//// + +Esse comando criará ou modificará algumas [variáveis ​​de ambiente](environment-variables.md){.internal-link target=_blank} que estarão disponíveis para os próximos comandos. + +Uma dessas variáveis ​​é a variável `PATH`. + +/// tip | "Dica" + +Você pode aprender mais sobre a variável de ambiente `PATH` na seção [Variáveis ​​de ambiente](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +A ativação de um ambiente virtual adiciona seu caminho `.venv/bin` (no Linux e macOS) ou `.venv\Scripts` (no Windows) à variável de ambiente `PATH`. + +Digamos que antes de ativar o ambiente, a variável `PATH` estava assim: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema procuraria programas em: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Isso significa que o sistema procuraria programas em: + +* `C:\Windows\System32` + +//// + +Após ativar o ambiente virtual, a variável `PATH` ficaria mais ou menos assim: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +e usa esse. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +e usa esse. + +//// + +Um detalhe importante é que ele colocará o caminho do ambiente virtual no **início** da variável `PATH`. O sistema o encontrará **antes** de encontrar qualquer outro Python disponível. Dessa forma, quando você executar `python`, ele usará o Python **do ambiente virtual** em vez de qualquer outro `python` (por exemplo, um `python` de um ambiente global). + +Ativar um ambiente virtual também muda algumas outras coisas, mas esta é uma das mais importantes. + +## Verificando um ambiente virtual + +Ao verificar se um ambiente virtual está ativo, por exemplo com: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
          + +//// + +Isso significa que o programa `python` que será usado é aquele **no ambiente virtual**. + +você usa `which` no Linux e macOS e `Get-Command` no Windows PowerShell. + +A maneira como esse comando funciona é que ele vai e verifica na variável de ambiente `PATH`, passando por **cada caminho em ordem**, procurando pelo programa chamado `python`. Uma vez que ele o encontre, ele **mostrará o caminho** para esse programa. + +A parte mais importante é que quando você chama ``python`, esse é exatamente o "`python`" que será executado. + +Assim, você pode confirmar se está no ambiente virtual correto. + +/// tip | "Dica" + +É fácil ativar um ambiente virtual, obter um Python e então **ir para outro projeto**. + +E o segundo projeto **não funcionaria** porque você está usando o **Python incorreto**, de um ambiente virtual para outro projeto. + +É útil poder verificar qual `python` está sendo usado. 🤓 + +/// + +## Por que desativar um ambiente virtual + +Por exemplo, você pode estar trabalhando em um projeto `philosophers-stone`, **ativar esse ambiente virtual**, instalar pacotes e trabalhar com esse ambiente. + +E então você quer trabalhar em **outro projeto** `prisoner-of-azkaban`. + +Você vai para aquele projeto: + +
          + +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
          + +Se você não desativar o ambiente virtual para `philosophers-stone`, quando você executar `python` no terminal, ele tentará usar o Python de `philosophers-stone`. + +
          + +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Erro ao importar o Sirius, ele não está instalado 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
          + +Mas se você desativar o ambiente virtual e ativar o novo para `prisoner-of-askaban`, quando você executar `python`, ele usará o Python do ambiente virtual em `prisoner-of-azkaban`. + +
          + +```console +$ cd ~/code/prisoner-of-azkaban + +// Você não precisa estar no diretório antigo para desativar, você pode fazer isso de onde estiver, mesmo depois de ir para o outro projeto 😎 +$ deactivate + +// Ative o ambiente virtual em prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Agora, quando você executar o python, ele encontrará o pacote sirius instalado neste ambiente virtual ✨ +$ python main.py + +Eu juro solenemente 🐺 +``` + +
          + +## Alternativas + +Este é um guia simples para você começar e lhe ensinar como tudo funciona **por baixo**. + +Existem muitas **alternativas** para gerenciar ambientes virtuais, dependências de pacotes (requisitos) e projetos. + +Quando estiver pronto e quiser usar uma ferramenta para **gerenciar todo o projeto**, dependências de pacotes, ambientes virtuais, etc., sugiro que você experimente o uv. + +`uv` pode fazer muitas coisas, ele pode: + +* **Instalar o Python** para você, incluindo versões diferentes +* Gerenciar o **ambiente virtual** para seus projetos +* Instalar **pacotes** +* Gerenciar **dependências e versões** de pacotes para seu projeto +* Certifique-se de ter um conjunto **exato** de pacotes e versões para instalar, incluindo suas dependências, para que você possa ter certeza de que pode executar seu projeto em produção exatamente da mesma forma que em seu computador durante o desenvolvimento, isso é chamado de **bloqueio** +* E muitas outras coisas + +## Conclusão + +Se você leu e entendeu tudo isso, agora **você sabe muito mais** sobre ambientes virtuais do que muitos desenvolvedores por aí. 🤓 + +Saber esses detalhes provavelmente será útil no futuro, quando você estiver depurando algo que parece complexo, mas você saberá **como tudo funciona**. 😎 From eb45bade63972dec674b83524e010e19ebdcd457 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Sep 2024 10:37:36 +0000 Subject: [PATCH 246/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7492242a4..114841f2d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/testing.md`. PR [#12164](https://github.com/fastapi/fastapi/pull/12164) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126). From a4c5f7f62fbb2fbfc3daefd3ddcefa8b65e103d8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Sep 2024 10:38:58 +0000 Subject: [PATCH 247/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 114841f2d..11289cfe8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/environment-variables.md`. PR [#12162](https://github.com/fastapi/fastapi/pull/12162) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/testing.md`. PR [#12164](https://github.com/fastapi/fastapi/pull/12164) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126). From 74451189f6f243833674fc22a1fe57dfb21f9831 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Sep 2024 10:40:52 +0000 Subject: [PATCH 248/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 11289cfe8..a72775416 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/virtual-environments.md`. PR [#12163](https://github.com/fastapi/fastapi/pull/12163) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/environment-variables.md`. PR [#12162](https://github.com/fastapi/fastapi/pull/12162) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/testing.md`. PR [#12164](https://github.com/fastapi/fastapi/pull/12164) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus). From b0eedbb5804a6ac32e4ee8d029d462d950ff8848 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 11 Sep 2024 09:45:30 +0200 Subject: [PATCH 249/356] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Improve=20performa?= =?UTF-8?q?nce=20in=20request=20body=20parsing=20with=20a=20cache=20for=20?= =?UTF-8?q?internal=20model=20fields=20(#12184)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/_compat.py | 6 ++++++ fastapi/dependencies/utils.py | 4 ++-- tests/test_compat.py | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index f940d6597..4b07b44fa 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -2,6 +2,7 @@ from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum +from functools import lru_cache from typing import ( Any, Callable, @@ -649,3 +650,8 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool: is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) for sub_annotation in get_args(annotation) ) + + +@lru_cache +def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return get_model_fields(model) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 6083b7319..f18eace9d 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -32,8 +32,8 @@ from fastapi._compat import ( evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, + get_cached_model_fields, get_missing_field_error, - get_model_fields, is_bytes_field, is_bytes_sequence_field, is_scalar_field, @@ -810,7 +810,7 @@ async def request_body_to_args( fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): - fields_to_extract = get_model_fields(first_field.type_) + fields_to_extract = get_cached_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) diff --git a/tests/test_compat.py b/tests/test_compat.py index 270475bf3..f4a3093c5 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -5,6 +5,7 @@ from fastapi._compat import ( ModelField, Undefined, _get_model_config, + get_cached_model_fields, get_model_fields, is_bytes_sequence_annotation, is_scalar_field, @@ -102,3 +103,18 @@ def test_is_pv1_scalar_field(): fields = get_model_fields(Model) assert not is_scalar_field(fields[0]) + + +def test_get_model_fields_cached(): + class Model(BaseModel): + foo: str + + non_cached_fields = get_model_fields(Model) + non_cached_fields2 = get_model_fields(Model) + cached_fields = get_cached_model_fields(Model) + cached_fields2 = get_cached_model_fields(Model) + for f1, f2 in zip(cached_fields, cached_fields2): + assert f1 is f2 + + assert non_cached_fields is not non_cached_fields2 + assert cached_fields is cached_fields2 From 8dc882f75121414eb44db590efae83fbddf43f72 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 11 Sep 2024 07:45:49 +0000 Subject: [PATCH 250/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a72775416..647b51b19 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ⚡️ Improve performance in request body parsing with a cache for internal model fields. PR [#12184](https://github.com/fastapi/fastapi/pull/12184) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Remove duplicate line in docs for `docs/en/docs/environment-variables.md`. PR [#12169](https://github.com/fastapi/fastapi/pull/12169) by [@prometek](https://github.com/prometek). From 212fd5e247279073dceaba346fd4afc52f627232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 11 Sep 2024 09:46:34 +0200 Subject: [PATCH 251/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?4.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 647b51b19..97f472815 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.114.1 + ### Refactors * ⚡️ Improve performance in request body parsing with a cache for internal model fields. PR [#12184](https://github.com/fastapi/fastapi/pull/12184) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index dce17360f..c2ed4859a 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.114.0" +__version__ = "0.114.1" from starlette import status as status From 24b8f2668beb773895a93040a2ae284898dc58b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 12 Sep 2024 00:49:55 +0200 Subject: [PATCH 252/356] =?UTF-8?q?=E2=9E=95=20Add=20inline-snapshot=20for?= =?UTF-8?q?=20tests=20(#12189)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++++ requirements-tests.txt | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index bb87be470..1be2817a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -241,3 +241,7 @@ known-third-party = ["fastapi", "pydantic", "starlette"] [tool.ruff.lint.pyupgrade] # Preserve types, even if a file imports `from __future__ import annotations`. keep-runtime-typing = true + +[tool.inline-snapshot] +# default-flags=["fix"] +# default-flags=["create"] diff --git a/requirements-tests.txt b/requirements-tests.txt index 809a19c0c..2f2576dd5 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -14,7 +14,7 @@ anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 - +inline-snapshot==0.13.0 # types types-ujson ==5.7.0.1 types-orjson ==3.6.2 From ba0bb6212e553e779f75f973d07a4db112b43cf0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 11 Sep 2024 22:50:18 +0000 Subject: [PATCH 253/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 97f472815..01c9fb225 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ➕ Add inline-snapshot for tests. PR [#12189](https://github.com/fastapi/fastapi/pull/12189) by [@tiangolo](https://github.com/tiangolo). + ## 0.114.1 ### Refactors From c8e644d19e688e00e51cdca2c1bb15d274d70801 Mon Sep 17 00:00:00 2001 From: Max Scheijen <47034840+maxscheijen@users.noreply.github.com> Date: Thu, 12 Sep 2024 19:00:36 +0200 Subject: [PATCH 254/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Dutch=20translatio?= =?UTF-8?q?n=20for=20`docs/nl/docs/python-types.md`=20(#12158)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/nl/docs/python-types.md | 597 +++++++++++++++++++++++++++++++++++ 1 file changed, 597 insertions(+) create mode 100644 docs/nl/docs/python-types.md diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md new file mode 100644 index 000000000..a5562b795 --- /dev/null +++ b/docs/nl/docs/python-types.md @@ -0,0 +1,597 @@ +# Introductie tot Python Types + +Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd). + +Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd. + +Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen. + +Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig. + +**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen. + +Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren. + +/// note + +Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over. + +/// + +## Motivatie + +Laten we beginnen met een eenvoudig voorbeeld: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +Het aanroepen van dit programma leidt tot het volgende resultaat: + +``` +John Doe +``` + +De functie voert het volgende uit: + +* Neem een `first_name` en een `last_name` +* Converteer de eerste letter van elk naar een hoofdletter met `title()`. +`` +* Voeg samen met een spatie in het midden. + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### Bewerk het + +Dit is een heel eenvoudig programma. + +Maar stel je nu voor dat je het vanaf nul zou moeten maken. + +Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar... + +Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen. + +Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`? + +Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor. + +Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren. + +Maar helaas krijg je niets bruikbaars: + + + +### Types toevoegen + +Laten we een enkele regel uit de vorige versie aanpassen. + +We zullen precies dit fragment, de parameters van de functie, wijzigen van: + +```Python + first_name, last_name +``` + +naar: + +```Python + first_name: str, last_name: str +``` + +Dat is alles. + +Dat zijn de "type hints": + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: + +```Python + first_name="john", last_name="doe" +``` + +Het is iets anders. + +We gebruiken dubbele punten (`:`), geen gelijkheidstekens (`=`). + +Het toevoegen van type hints verandert normaal gesproken niet wat er gebeurt in je programma t.o.v. wat er zonder type hints zou gebeuren. + +Maar stel je voor dat je weer bezig bent met het maken van een functie, maar deze keer met type hints. + +Op hetzelfde moment probeer je de automatische aanvulling te activeren met `Ctrl+Spatie` en je ziet: + + + +Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt die “een belletje doet rinkelen”: + + + +### Meer motivatie + +Bekijk deze functie, deze heeft al type hints: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: + + + +Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## Types declareren + +Je hebt net de belangrijkste plek om type hints te declareren gezien. Namelijk als functieparameters. + +Dit is ook de belangrijkste plek waar je ze gebruikt met **FastAPI**. + +### Eenvoudige types + +Je kunt alle standaard Python types declareren, niet alleen `str`. + +Je kunt bijvoorbeeld het volgende gebruiken: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### Generieke types met typeparameters + +Er zijn enkele datastructuren die andere waarden kunnen bevatten, zoals `dict`, `list`, `set` en `tuple` en waar ook de interne waarden hun eigen type kunnen hebben. + +Deze types die interne types hebben worden “**generieke**” types genoemd. Het is mogelijk om ze te declareren, zelfs met hun interne types. + +Om deze types en de interne types te declareren, kun je de standaard Python module `typing` gebruiken. Deze module is speciaal gemaakt om deze type hints te ondersteunen. + +#### Nieuwere versies van Python + +De syntax met `typing` is **verenigbaar** met alle versies, van Python 3.6 tot aan de nieuwste, inclusief Python 3.9, Python 3.10, enz. + +Naarmate Python zich ontwikkelt, worden **nieuwere versies**, met verbeterde ondersteuning voor deze type annotaties, beschikbaar. In veel gevallen hoef je niet eens de `typing` module te importeren en te gebruiken om de type annotaties te declareren. + +Als je een recentere versie van Python kunt kiezen voor je project, kun je profiteren van die extra eenvoud. + +In alle documentatie staan voorbeelden die compatibel zijn met elke versie van Python (als er een verschil is). + +Bijvoorbeeld “**Python 3.6+**” betekent dat het compatibel is met Python 3.6 of hoger (inclusief 3.7, 3.8, 3.9, 3.10, etc). En “**Python 3.9+**” betekent dat het compatibel is met Python 3.9 of hoger (inclusief 3.10, etc). + +Als je de **laatste versies van Python** kunt gebruiken, gebruik dan de voorbeelden voor de laatste versie, die hebben de **beste en eenvoudigste syntax**, bijvoorbeeld “**Python 3.10+**”. + +#### List + +Laten we bijvoorbeeld een variabele definiëren als een `list` van `str`. + +//// tab | Python 3.9+ + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Als type, vul `list` in. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Van `typing`, importeer `List` (met een hoofdletter `L`): + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Zet als type de `List` die je hebt geïmporteerd uit `typing`. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="4" +{!> ../../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// info + +De interne types tussen vierkante haakjes worden “typeparameters” genoemd. + +In dit geval is `str` de typeparameter die wordt doorgegeven aan `List` (of `list` in Python 3.9 en hoger). + +/// + +Dat betekent: “de variabele `items` is een `list`, en elk van de items in deze list is een `str`”. + +/// tip + +Als je Python 3.9 of hoger gebruikt, hoef je `List` niet te importeren uit `typing`, je kunt in plaats daarvan hetzelfde reguliere `list` type gebruiken. + +/// + +Door dat te doen, kan je editor ondersteuning bieden, zelfs tijdens het verwerken van items uit de list: + + + +Zonder types is dat bijna onmogelijk om te bereiken. + +Merk op dat de variabele `item` een van de elementen is in de lijst `items`. + +Toch weet de editor dat het een `str` is, en biedt daar vervolgens ondersteuning voor aan. + +#### Tuple en Set + +Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial007.py!} +``` + +//// + +Dit betekent: + +* De variabele `items_t` is een `tuple` met 3 items, een `int`, nog een `int`, en een `str`. +* De variabele `items_s` is een `set`, en elk van de items is van het type `bytes`. + +#### Dict + +Om een `dict` te definiëren, geef je 2 typeparameters door, gescheiden door komma's. + +De eerste typeparameter is voor de sleutels (keys) van de `dict`. + +De tweede typeparameter is voor de waarden (values) van het `dict`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008.py!} +``` + +//// + +Dit betekent: + +* De variabele `prices` is een `dict`: + * De sleutels van dit `dict` zijn van het type `str` (bijvoorbeeld de naam van elk item). + * De waarden van dit `dict` zijn van het type `float` (bijvoorbeeld de prijs van elk item). + +#### Union + +Je kunt een variable declareren die van **verschillende types** kan zijn, bijvoorbeeld een `int` of een `str`. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het `Union`-type van `typing` gebruiken en de mogelijke types die je wilt accepteren, tussen de vierkante haakjes zetten. + +In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt scheiden door een verticale balk (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +In beide gevallen betekent dit dat `item` een `int` of een `str` kan zijn. + +#### Mogelijk `None` + +Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het ook `None` kan zijn. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module. + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn. + +`Optional[EenType]` is eigenlijk een snelkoppeling voor `Union[EenType, None]`, ze zijn equivalent. + +Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Gebruik van `Union` of `Optional` + +Als je een Python versie lager dan 3.10 gebruikt, is dit een tip vanuit mijn **subjectieve** standpunt: + +* 🚨 Vermijd het gebruik van `Optional[EenType]`. +* Gebruik in plaats daarvan **`Union[EenType, None]`** ✨. + +Beide zijn gelijkwaardig en onderliggend zijn ze hetzelfde, maar ik zou `Union` aanraden in plaats van `Optional` omdat het woord “**optional**” lijkt te impliceren dat de waarde optioneel is, en het eigenlijk betekent “het kan `None` zijn”, zelfs als het niet optioneel is en nog steeds vereist is. + +Ik denk dat `Union[SomeType, None]` explicieter is over wat het betekent. + +Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed hebben op hoe jij en je teamgenoten over de code denken. + +Laten we als voorbeeld deze functie nemen: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c.py!} +``` + +De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: + +```Python +say_hi() # Oh, nee, dit geeft een foutmelding! 😱 +``` + +De `name` parameter is **nog steeds vereist** (niet *optioneel*) omdat het geen standaardwaarde heeft. Toch accepteert `name` `None` als waarde: + +```Python +say_hi(name=None) # Dit werkt, None is geldig 🎉 +``` + +Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009c_py310.py!} +``` + +Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 + +#### Generieke typen + +De types die typeparameters in vierkante haakjes gebruiken, worden **Generieke types** of **Generics** genoemd, bijvoorbeeld: + +//// tab | Python 3.10+ + +Je kunt dezelfde ingebouwde types gebruiken als generics (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +Hetzelfde als bij Python 3.8, uit de `typing`-module: + +* `Union` +* `Optional` (hetzelfde als bij Python 3.8) +* ...en anderen. + +In Python 3.10 kun je , als alternatief voor de generieke `Union` en `Optional`, de verticale lijn (`|`) gebruiken om unions van typen te voorzien, dat is veel beter en eenvoudiger. + +//// + +//// tab | Python 3.9+ + +Je kunt dezelfde ingebouwde types gebruiken als generieke types (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +En hetzelfde als met Python 3.8, vanuit de `typing`-module: + +* `Union` +* `Optional` +* ...en anderen. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...en anderen. + +//// + +### Klassen als types + +Je kunt een klasse ook declareren als het type van een variabele. + +Stel dat je een klasse `Person` hebt, met een naam: + +```Python hl_lines="1-3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Vervolgens kun je een variabele van het type `Persoon` declareren: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +Dan krijg je ook nog eens volledige editorondersteuning: + + + +Merk op dat dit betekent dat "`one_person` een **instantie** is van de klasse `Person`". + +Dit betekent niet dat `one_person` de **klasse** is met de naam `Person`. + +## Pydantic modellen + +Pydantic is een Python-pakket voor het uitvoeren van datavalidatie. + +Je declareert de "vorm" van de data als klassen met attributen. + +Elk attribuut heeft een type. + +Vervolgens maak je een instantie van die klasse met een aantal waarden en het valideert de waarden, converteert ze naar het juiste type (als dat het geval is) en geeft je een object met alle data terug. + +Daarnaast krijg je volledige editorondersteuning met dat resulterende object. + +Een voorbeeld uit de officiële Pydantic-documentatie: + +//// tab | Python 3.10+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Om meer te leren over Pydantic, bekijk de documentatie. + +/// + +**FastAPI** is volledig gebaseerd op Pydantic. + +Je zult veel meer van dit alles in de praktijk zien in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +/// tip + +Pydantic heeft een speciaal gedrag wanneer je `Optional` of `Union[EenType, None]` gebruikt zonder een standaardwaarde, je kunt er meer over lezen in de Pydantic-documentatie over Verplichte optionele velden. + +/// + +## Type Hints met Metadata Annotaties + +Python heeft ook een functie waarmee je **extra metadata** in deze type hints kunt toevoegen met behulp van `Annotated`. + +//// tab | Python 3.9+ + +In Python 3.9 is `Annotated` onderdeel van de standaardpakket, dus je kunt het importeren vanuit `typing`. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensions`. + +Het wordt al geïnstalleerd met **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python zelf doet niets met deze `Annotated` en voor editors en andere hulpmiddelen is het type nog steeds een `str`. + +Maar je kunt deze ruimte in `Annotated` gebruiken om **FastAPI** te voorzien van extra metadata over hoe je wilt dat je applicatie zich gedraagt. + +Het belangrijkste om te onthouden is dat **de eerste *typeparameter*** die je doorgeeft aan `Annotated` het **werkelijke type** is. De rest is gewoon metadata voor andere hulpmiddelen. + +Voor nu hoef je alleen te weten dat `Annotated` bestaat en dat het standaard Python is. 😎 + +Later zul je zien hoe **krachtig** het kan zijn. + +/// tip + +Het feit dat dit **standaard Python** is, betekent dat je nog steeds de **best mogelijke ontwikkelaarservaring** krijgt in je editor, met de hulpmiddelen die je gebruikt om je code te analyseren en te refactoren, enz. ✨ + +Daarnaast betekent het ook dat je code zeer verenigbaar zal zijn met veel andere Python-hulpmiddelen en -pakketten. 🚀 + +/// + +## Type hints in **FastAPI** + +**FastAPI** maakt gebruik van type hints om verschillende dingen te doen. + +Met **FastAPI** declareer je parameters met type hints en krijg je: + +* **Editor ondersteuning**. +* **Type checks**. + +...en **FastAPI** gebruikt dezelfde declaraties om: + +* **Vereisten te definïeren **: van request pad parameters, query parameters, headers, bodies, dependencies, enz. +* **Data te converteren**: van de request naar het vereiste type. +* **Data te valideren**: afkomstig van elke request: + * **Automatische foutmeldingen** te genereren die naar de client worden geretourneerd wanneer de data ongeldig is. +* De API met OpenAPI te **documenteren**: + * die vervolgens wordt gebruikt door de automatische interactieve documentatie gebruikersinterfaces. + +Dit klinkt misschien allemaal abstract. Maak je geen zorgen. Je ziet dit allemaal in actie in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +Het belangrijkste is dat door standaard Python types te gebruiken, op één plek (in plaats van meer klassen, decorators, enz. toe te voegen), **FastAPI** een groot deel van het werk voor je doet. + +/// info + +Als je de hele tutorial al hebt doorgenomen en terug bent gekomen om meer te weten te komen over types, is een goede bron het "cheat sheet" van `mypy`. + +/// From 492943fdb1f726800ab7a42ead08e297813c8e68 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Sep 2024 17:01:01 +0000 Subject: [PATCH 255/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01c9fb225..c3bf2bb8d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Dutch translation for `docs/nl/docs/python-types.md`. PR [#12158](https://github.com/fastapi/fastapi/pull/12158) by [@maxscheijen](https://github.com/maxscheijen). + ### Internal * ➕ Add inline-snapshot for tests. PR [#12189](https://github.com/fastapi/fastapi/pull/12189) by [@tiangolo](https://github.com/tiangolo). From 4a94fe3c8249e2c13999964ac9f707ab0ca069ee Mon Sep 17 00:00:00 2001 From: Waket Zheng Date: Fri, 13 Sep 2024 01:01:54 +0800 Subject: [PATCH 256/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/project-generation.md`=20(#12170)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/project-generation.md | 112 ++++++++--------------------- 1 file changed, 28 insertions(+), 84 deletions(-) diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md index 0655cb0a9..9b3735539 100644 --- a/docs/zh/docs/project-generation.md +++ b/docs/zh/docs/project-generation.md @@ -1,84 +1,28 @@ -# 项目生成 - 模板 - -项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。 - -项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。 - -## 全栈 FastAPI + PostgreSQL - -GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql - -### 全栈 FastAPI + PostgreSQL - 功能 - -* 完整的 **Docker** 集成(基于 Docker) -* Docker Swarm 开发模式 -* **Docker Compose** 本地开发集成与优化 -* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn -* Python **FastAPI** 后端: -* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic) - * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间 - * **简单**:易学、易用,阅读文档所需时间更短 - * **简短**:代码重复最小化,每次参数声明都可以实现多个功能 - * **健壮**: 生产级别的代码,还有自动交互文档 - * **基于标准**:完全兼容并基于 API 开放标准:OpenAPIJSON Schema - * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等 -* **安全密码**,默认使用密码哈希 -* **JWT 令牌**身份验证 -* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker) -* 基础的用户模型(可按需修改或删除) -* **Alembic** 迁移 -* **CORS**(跨域资源共享) -* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码 -* REST 后端测试基于 Pytest,并与 Docker 集成,可独立于数据库实现完整的 API 交互测试。因为是在 Docker 中运行,每次都可从头构建新的数据存储(使用 ElasticSearch、MongoDB、CouchDB 等数据库,仅测试 API 运行) -* Python 与 **Jupyter Kernels** 集成,用于远程或 Docker 容器内部开发,使用 Atom Hydrogen 或 Visual Studio Code 的 Jupyter 插件 -* **Vue** 前端: - * 由 Vue CLI 生成 - * **JWT 身份验证**处理 - * 登录视图 - * 登录后显示主仪表盘视图 - * 主仪表盘支持用户创建与编辑 - * 用户信息编辑 - * **Vuex** - * **Vue-router** - * **Vuetify** 美化组件 - * **TypeScript** - * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置) - * Docker 多阶段构建,无需保存或提交编译的代码 - * 在构建时运行前端测试(可禁用) - * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容 -* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL -* 使用 **Flower** 监控 Celery 任务 -* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务 -* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证 -* GitLab **CI**(持续集成),包括前后端测试 - -## 全栈 FastAPI + Couchbase - -GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase - -⚠️ **警告** ⚠️ - -如果您想从头开始创建新项目,建议使用以下备选方案。 - -例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。 - -当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。 - -详见资源仓库中的文档。 - -## 全栈 FastAPI + MongoDB - -……敬请期待,得看我有没有时间做这个项目。😅 🎉 - -## FastAPI + spaCy 机器学习模型 - -GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi - -### FastAPI + spaCy 机器学习模型 - 功能 - -* 集成 **spaCy** NER 模型 -* 内置 **Azure 认知搜索**请求格式 -* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn -* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发 -* **多语**支持,可在项目设置时选择 spaCy 内置的语言 -* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow) +# FastAPI全栈模板 + +模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁 + +您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。 + +代码仓: Full Stack FastAPI Template + +## FastAPI全栈模板 - 技术栈和特性 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。 + - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。 + - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。 +- 🚀 [React](https://react.dev) 用于前端。 + - 💃 使用了TypeScript、hooks、Vite和其他一些现代化的前端技术栈。 + - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。 + - 🤖 一个自动化生成的前端客户端。 + - 🧪 Playwright用于端到端测试。 + - 🦇 支持暗黑主题(Dark mode)。 +- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。 +- 🔒 默认使用密码哈希来保证安全。 +- 🔑 JWT令牌用于权限验证。 +- 📫 使用邮箱来进行密码恢复。 +- ✅ 单元测试用了[Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。 +- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。 +- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。 From 93e50e373b0651c22a6743a4e907dafbadc8d27e Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Sep 2024 17:03:26 +0000 Subject: [PATCH 257/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3bf2bb8d..ac2398759 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#12170](https://github.com/fastapi/fastapi/pull/12170) by [@waketzheng](https://github.com/waketzheng). * 🌐 Add Dutch translation for `docs/nl/docs/python-types.md`. PR [#12158](https://github.com/fastapi/fastapi/pull/12158) by [@maxscheijen](https://github.com/maxscheijen). ### Internal From e50facaf227f4725d64c7166c2fe3438367705c7 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Thu, 12 Sep 2024 14:03:48 -0300 Subject: [PATCH 258/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/request-form-models.md`?= =?UTF-8?q?=20(#12175)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request-form-models.md | 134 +++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 docs/pt/docs/tutorial/request-form-models.md diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..a9db18e9d --- /dev/null +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -0,0 +1,134 @@ +# Modelos de Formulários + +Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI. + +/// info | "Informação" + +Para utilizar formulários, instale primeiramente o `python-multipart`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo, e então instalar. Por exemplo: + +```console +$ pip install python-multipart +``` + +/// + +/// note | "Nota" + +Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 + +/// + +## Modelos Pydantic para Formulários + +Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9-11 15" +{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-10 14" +{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7-9 13" +{!> ../../../docs_src/request_form_models/tutorial001.py!} +``` + +//// + +O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. + +## Confira os Documentos + +Você pode verificar na UI de documentação em `/docs`: + +
          + +
          + +## Proibir Campos Extras de Formulários + +Em alguns casos de uso especiais (provavelmente não muito comum), você pode desejar **restringir** os campos do formulário para aceitar apenas os declarados no modelo Pydantic. E **proibir** qualquer campo **extra**. + +/// note | "Nota" + +Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 + +/// + +Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/request_form_models/tutorial002.py!} +``` + +//// + +Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar os campos de formulário: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Ele receberá um retorno de erro informando-o que o campo `extra` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Resumo + +Você pode utilizar modelos Pydantic para declarar campos de formulários no FastAPI. 😎 From ed66d705139b67665db1742797fdbeba7490c0e2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Sep 2024 17:06:34 +0000 Subject: [PATCH 259/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ac2398759..6534adb03 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-form-models.md`. PR [#12175](https://github.com/fastapi/fastapi/pull/12175) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#12170](https://github.com/fastapi/fastapi/pull/12170) by [@waketzheng](https://github.com/waketzheng). * 🌐 Add Dutch translation for `docs/nl/docs/python-types.md`. PR [#12158](https://github.com/fastapi/fastapi/pull/12158) by [@maxscheijen](https://github.com/maxscheijen). From 2a4351105ed968002ad15530dec35c6bb453a042 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 13 Sep 2024 11:14:46 +0200 Subject: [PATCH 260/356] =?UTF-8?q?=F0=9F=92=A1=20Add=20comments=20with=20?= =?UTF-8?q?instructions=20for=20Playwright=20screenshot=20scripts=20(#1219?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/playwright/request_form_models/image01.py | 4 +++- scripts/playwright/separate_openapi_schemas/image01.py | 3 +++ scripts/playwright/separate_openapi_schemas/image02.py | 3 +++ scripts/playwright/separate_openapi_schemas/image03.py | 3 +++ scripts/playwright/separate_openapi_schemas/image04.py | 3 +++ scripts/playwright/separate_openapi_schemas/image05.py | 3 +++ 6 files changed, 18 insertions(+), 1 deletion(-) diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py index 15bd3858c..fe4da32fc 100644 --- a/scripts/playwright/request_form_models/image01.py +++ b/scripts/playwright/request_form_models/image01.py @@ -8,11 +8,13 @@ from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) - context = browser.new_context() + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="POST /login/ Login").click() page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") # --------------------- diff --git a/scripts/playwright/separate_openapi_schemas/image01.py b/scripts/playwright/separate_openapi_schemas/image01.py index 0b40f3bbc..0eb55fb73 100644 --- a/scripts/playwright/separate_openapi_schemas/image01.py +++ b/scripts/playwright/separate_openapi_schemas/image01.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("POST/items/Create Item").click() page.get_by_role("tab", name="Schema").first.click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image02.py b/scripts/playwright/separate_openapi_schemas/image02.py index f76af7ee2..0eb6c3c79 100644 --- a/scripts/playwright/separate_openapi_schemas/image02.py +++ b/scripts/playwright/separate_openapi_schemas/image02.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("button", name="Try it out").click() page.get_by_role("button", name="Execute").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image03.py b/scripts/playwright/separate_openapi_schemas/image03.py index 127f5c428..b68e9d7db 100644 --- a/scripts/playwright/separate_openapi_schemas/image03.py +++ b/scripts/playwright/separate_openapi_schemas/image03.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("tab", name="Schema").click() page.get_by_label("Schema").get_by_role("button", name="Expand all").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image04.py b/scripts/playwright/separate_openapi_schemas/image04.py index 208eaf8a0..a36c2f6b2 100644 --- a/scripts/playwright/separate_openapi_schemas/image04.py +++ b/scripts/playwright/separate_openapi_schemas/image04.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item-Input").click() page.get_by_role("button", name="Item-Output").click() page.set_viewport_size({"width": 960, "height": 820}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image05.py b/scripts/playwright/separate_openapi_schemas/image05.py index 83966b449..0da5db0cf 100644 --- a/scripts/playwright/separate_openapi_schemas/image05.py +++ b/scripts/playwright/separate_openapi_schemas/image05.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item", exact=True).click() page.set_viewport_size({"width": 960, "height": 700}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png" ) From 0fc6e34135b2436a8749f5aa3b8f8ad92da106d5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 13 Sep 2024 09:15:10 +0000 Subject: [PATCH 261/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6534adb03..f00c3fed3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Internal +* 💡 Add comments with instructions for Playwright screenshot scripts. PR [#12193](https://github.com/fastapi/fastapi/pull/12193) by [@tiangolo](https://github.com/tiangolo). * ➕ Add inline-snapshot for tests. PR [#12189](https://github.com/fastapi/fastapi/pull/12189) by [@tiangolo](https://github.com/tiangolo). ## 0.114.1 From 88d4f2cb1814392f54011b2bbd3fe55c5f2a3278 Mon Sep 17 00:00:00 2001 From: Nico Tonnhofer Date: Fri, 13 Sep 2024 11:51:00 +0200 Subject: [PATCH 262/356] =?UTF-8?q?=F0=9F=90=9B=20Fix=20form=20field=20reg?= =?UTF-8?q?ression=20(#12194)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 2 +- tests/test_forms_single_model.py | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f18eace9d..7548cf0c7 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -788,7 +788,7 @@ async def _extract_form_body( tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: - values[field.name] = value + values[field.alias] = value for key, value in received_body.items(): if key not in values: values[key] = value diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py index 7ed3ba3a2..880ab3820 100644 --- a/tests/test_forms_single_model.py +++ b/tests/test_forms_single_model.py @@ -3,7 +3,7 @@ from typing import List, Optional from dirty_equals import IsDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient -from pydantic import BaseModel +from pydantic import BaseModel, Field from typing_extensions import Annotated app = FastAPI() @@ -14,6 +14,7 @@ class FormModel(BaseModel): lastname: str age: Optional[int] = None tags: List[str] = ["foo", "bar"] + alias_with: str = Field(alias="with", default="nothing") @app.post("/form/") @@ -32,6 +33,7 @@ def test_send_all_data(): "lastname": "Sanchez", "age": "70", "tags": ["plumbus", "citadel"], + "with": "something", }, ) assert response.status_code == 200, response.text @@ -40,6 +42,7 @@ def test_send_all_data(): "lastname": "Sanchez", "age": 70, "tags": ["plumbus", "citadel"], + "with": "something", } @@ -51,6 +54,7 @@ def test_defaults(): "lastname": "Sanchez", "age": None, "tags": ["foo", "bar"], + "with": "nothing", } @@ -100,13 +104,13 @@ def test_no_data(): "type": "missing", "loc": ["body", "username"], "msg": "Field required", - "input": {"tags": ["foo", "bar"]}, + "input": {"tags": ["foo", "bar"], "with": "nothing"}, }, { "type": "missing", "loc": ["body", "lastname"], "msg": "Field required", - "input": {"tags": ["foo", "bar"]}, + "input": {"tags": ["foo", "bar"], "with": "nothing"}, }, ] } From 3a5fd71f5596ad7437394597fc09f1b8e8ec73f2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 13 Sep 2024 09:51:26 +0000 Subject: [PATCH 263/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f00c3fed3..9370a1f3f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Fix form field regression with `alias`. PR [#12194](https://github.com/fastapi/fastapi/pull/12194) by [@Wurstnase](https://github.com/Wurstnase). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-form-models.md`. PR [#12175](https://github.com/fastapi/fastapi/pull/12175) by [@ceb10n](https://github.com/ceb10n). From 2ada1615a338a415a0ad7a9b879a1e7c09b9cce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 13 Sep 2024 22:46:33 +0200 Subject: [PATCH 264/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?4.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9370a1f3f..3f0b60fd3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.114.2 + ### Fixes * 🐛 Fix form field regression with `alias`. PR [#12194](https://github.com/fastapi/fastapi/pull/12194) by [@Wurstnase](https://github.com/Wurstnase). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index c2ed4859a..3925d3603 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.114.1" +__version__ = "0.114.2" from starlette import status as status From 8eb3c5621ff2b946e7dd7a1a7ffd709e27de9ac6 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Sun, 15 Sep 2024 16:04:17 -0300 Subject: [PATCH 265/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/security/http-basic-auth.?= =?UTF-8?q?md`=20(#12195)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 docs/pt/docs/advanced/security/http-basic-auth.md diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..12b8ab01c --- /dev/null +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,192 @@ +# HTTP Basic Auth + +Para os casos mais simples, você pode utilizar o HTTP Basic Auth. + +No HTTP Basic Auth, a aplicação espera um cabeçalho que contém um usuário e uma senha. + +Caso ela não receba, ela retorna um erro HTTP 401 "Unauthorized" (*Não Autorizado*). + +E retorna um cabeçalho `WWW-Authenticate` com o valor `Basic`, e um parâmetro opcional `realm`. + +Isso sinaliza ao navegador para mostrar o prompt integrado para um usuário e senha. + +Então, quando você digitar o usuário e senha, o navegador os envia automaticamente no cabeçalho. + +## HTTP Basic Auth Simples + +* Importe `HTTPBasic` e `HTTPBasicCredentials`. +* Crie um "esquema `security`" utilizando `HTTPBasic`. +* Utilize o `security` com uma dependência em sua *operação de rota*. +* Isso retorna um objeto do tipo `HTTPBasicCredentials`: + * Isto contém o `username` e o `password` enviado. + +//// tab | Python 3.9+ + +```Python hl_lines="4 8 12" +{!> ../../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../../docs_src/security/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 6 10" +{!> ../../../docs_src/security/tutorial006.py!} +``` + +//// + +Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: + + + +## Verifique o usuário + +Aqui está um exemplo mais completo. + +Utilize uma dependência para verificar se o usuário e a senha estão corretos. + +Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha. + +O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em Inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. + +Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8. + +Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. + +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 12-24" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 11-21" +{!> ../../../docs_src/security/tutorial007.py!} +``` + +//// + +Isso seria parecido com: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +Porém ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "ataque de temporização (timing attacks)". + +### Ataques de Temporização + +Mas o que é um "ataque de temporização"? + +Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha. + +E eles enviam uma requisição com um usuário `johndoe` e uma senha `love123`. + +Então o código Python em sua aplicação seria equivalente a algo como: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos". + +Mas então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. + +E a sua aplicação faz algo como: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microsegundos a mais para retornar "Usuário ou senha incorretos". + +#### O tempo para responder ajuda os invasores + +Neste ponto, ao perceber que o servidor demorou alguns microsegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. + +E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`. + +#### Um ataque "profissional" + +Claro, os invasores não tentariam tudo isso de forma manual, eles escreveriam um programa para fazer isso, possivelmente com milhares ou milhões de testes por segundo. E obteriam apenas uma letra a mais por vez. + +Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o usuário e senha corretos, com a "ajuda" da nossa aplicação, apenas usando o tempo levado para responder. + +#### Corrija com o `secrets.compare_digest()` + +Mas em nosso código nós estamos utilizando o `secrets.compare_digest()`. + +Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha. + +Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela esterá a salvo contra toda essa gama de ataques de segurança. + + +### Retorne o erro + +Depois de detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: + +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | "Dica" + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="23-27" +{!> ../../../docs_src/security/tutorial007.py!} +``` + +//// From 35df20c79c8ce482c314934098e8875cf011c56e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Sep 2024 19:04:38 +0000 Subject: [PATCH 266/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3f0b60fd3..7f5e86b30 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12195](https://github.com/fastapi/fastapi/pull/12195) by [@ceb10n](https://github.com/ceb10n). + ## 0.114.2 ### Fixes From 4b2b14a8e89a46a3c37dbf49746c5cd0e6f678f2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 17 Sep 2024 00:00:09 +0200 Subject: [PATCH 267/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12204)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.4 → v0.6.5](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.4...v0.6.5) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f74816f12..4b1b10a68 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.4 + rev: v0.6.5 hooks: - id: ruff args: From 0903da78c9940b094e13732264b5e462a426e5cc Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 16 Sep 2024 22:00:35 +0000 Subject: [PATCH 268/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7f5e86b30..d6d2a05b3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12195](https://github.com/fastapi/fastapi/pull/12195) by [@ceb10n](https://github.com/ceb10n). +### Internal + +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12204](https://github.com/fastapi/fastapi/pull/12204) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + ## 0.114.2 ### Fixes From 55035f440bf852f739e3ccd71b67034016ae9bba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 17 Sep 2024 20:54:10 +0200 Subject: [PATCH 269/356] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20Pydan?= =?UTF-8?q?tic=20models=20for=20parameters=20using=20`Query`,=20`Cookie`,?= =?UTF-8?q?=20`Header`=20(#12199)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/cookie-param-models/image01.png | Bin 0 -> 45217 bytes .../tutorial/header-param-models/image01.png | Bin 0 -> 62257 bytes .../tutorial/query-param-models/image01.png | Bin 0 -> 45571 bytes docs/en/docs/tutorial/cookie-param-models.md | 154 ++++++++++ docs/en/docs/tutorial/header-param-models.md | 184 ++++++++++++ docs/en/docs/tutorial/query-param-models.md | 196 ++++++++++++ docs/en/mkdocs.yml | 3 + docs_src/cookie_param_models/tutorial001.py | 17 ++ .../cookie_param_models/tutorial001_an.py | 18 ++ .../tutorial001_an_py310.py | 17 ++ .../tutorial001_an_py39.py | 17 ++ .../cookie_param_models/tutorial001_py310.py | 15 + docs_src/cookie_param_models/tutorial002.py | 19 ++ .../cookie_param_models/tutorial002_an.py | 20 ++ .../tutorial002_an_py310.py | 19 ++ .../tutorial002_an_py39.py | 19 ++ .../cookie_param_models/tutorial002_pv1.py | 20 ++ .../cookie_param_models/tutorial002_pv1_an.py | 21 ++ .../tutorial002_pv1_an_py310.py | 20 ++ .../tutorial002_pv1_an_py39.py | 20 ++ .../tutorial002_pv1_py310.py | 18 ++ .../cookie_param_models/tutorial002_py310.py | 17 ++ docs_src/header_param_models/tutorial001.py | 19 ++ .../header_param_models/tutorial001_an.py | 20 ++ .../tutorial001_an_py310.py | 19 ++ .../tutorial001_an_py39.py | 19 ++ .../header_param_models/tutorial001_py310.py | 17 ++ .../header_param_models/tutorial001_py39.py | 19 ++ docs_src/header_param_models/tutorial002.py | 21 ++ .../header_param_models/tutorial002_an.py | 22 ++ .../tutorial002_an_py310.py | 21 ++ .../tutorial002_an_py39.py | 21 ++ .../header_param_models/tutorial002_pv1.py | 22 ++ .../header_param_models/tutorial002_pv1_an.py | 23 ++ .../tutorial002_pv1_an_py310.py | 22 ++ .../tutorial002_pv1_an_py39.py | 22 ++ .../tutorial002_pv1_py310.py | 20 ++ .../tutorial002_pv1_py39.py | 22 ++ .../header_param_models/tutorial002_py310.py | 19 ++ .../header_param_models/tutorial002_py39.py | 21 ++ docs_src/query_param_models/tutorial001.py | 19 ++ docs_src/query_param_models/tutorial001_an.py | 19 ++ .../tutorial001_an_py310.py | 18 ++ .../query_param_models/tutorial001_an_py39.py | 17 ++ .../query_param_models/tutorial001_py310.py | 18 ++ .../query_param_models/tutorial001_py39.py | 17 ++ docs_src/query_param_models/tutorial002.py | 21 ++ docs_src/query_param_models/tutorial002_an.py | 21 ++ .../tutorial002_an_py310.py | 20 ++ .../query_param_models/tutorial002_an_py39.py | 19 ++ .../query_param_models/tutorial002_pv1.py | 22 ++ .../query_param_models/tutorial002_pv1_an.py | 22 ++ .../tutorial002_pv1_an_py310.py | 21 ++ .../tutorial002_pv1_an_py39.py | 20 ++ .../tutorial002_pv1_py310.py | 21 ++ .../tutorial002_pv1_py39.py | 20 ++ .../query_param_models/tutorial002_py310.py | 20 ++ .../query_param_models/tutorial002_py39.py | 19 ++ fastapi/dependencies/utils.py | 90 +++++- fastapi/openapi/utils.py | 86 +++--- .../playwright/cookie_param_models/image01.py | 39 +++ .../playwright/header_param_models/image01.py | 38 +++ .../playwright/query_param_models/image01.py | 41 +++ .../test_cookie_param_models/__init__.py | 0 .../test_tutorial001.py | 205 +++++++++++++ .../test_tutorial002.py | 233 +++++++++++++++ .../test_header_param_models/__init__.py | 0 .../test_tutorial001.py | 238 +++++++++++++++ .../test_tutorial002.py | 249 ++++++++++++++++ .../test_query_param_models/__init__.py | 0 .../test_tutorial001.py | 260 ++++++++++++++++ .../test_tutorial002.py | 282 ++++++++++++++++++ 72 files changed, 3253 insertions(+), 45 deletions(-) create mode 100644 docs/en/docs/img/tutorial/cookie-param-models/image01.png create mode 100644 docs/en/docs/img/tutorial/header-param-models/image01.png create mode 100644 docs/en/docs/img/tutorial/query-param-models/image01.png create mode 100644 docs/en/docs/tutorial/cookie-param-models.md create mode 100644 docs/en/docs/tutorial/header-param-models.md create mode 100644 docs/en/docs/tutorial/query-param-models.md create mode 100644 docs_src/cookie_param_models/tutorial001.py create mode 100644 docs_src/cookie_param_models/tutorial001_an.py create mode 100644 docs_src/cookie_param_models/tutorial001_an_py310.py create mode 100644 docs_src/cookie_param_models/tutorial001_an_py39.py create mode 100644 docs_src/cookie_param_models/tutorial001_py310.py create mode 100644 docs_src/cookie_param_models/tutorial002.py create mode 100644 docs_src/cookie_param_models/tutorial002_an.py create mode 100644 docs_src/cookie_param_models/tutorial002_an_py310.py create mode 100644 docs_src/cookie_param_models/tutorial002_an_py39.py create mode 100644 docs_src/cookie_param_models/tutorial002_pv1.py create mode 100644 docs_src/cookie_param_models/tutorial002_pv1_an.py create mode 100644 docs_src/cookie_param_models/tutorial002_pv1_an_py310.py create mode 100644 docs_src/cookie_param_models/tutorial002_pv1_an_py39.py create mode 100644 docs_src/cookie_param_models/tutorial002_pv1_py310.py create mode 100644 docs_src/cookie_param_models/tutorial002_py310.py create mode 100644 docs_src/header_param_models/tutorial001.py create mode 100644 docs_src/header_param_models/tutorial001_an.py create mode 100644 docs_src/header_param_models/tutorial001_an_py310.py create mode 100644 docs_src/header_param_models/tutorial001_an_py39.py create mode 100644 docs_src/header_param_models/tutorial001_py310.py create mode 100644 docs_src/header_param_models/tutorial001_py39.py create mode 100644 docs_src/header_param_models/tutorial002.py create mode 100644 docs_src/header_param_models/tutorial002_an.py create mode 100644 docs_src/header_param_models/tutorial002_an_py310.py create mode 100644 docs_src/header_param_models/tutorial002_an_py39.py create mode 100644 docs_src/header_param_models/tutorial002_pv1.py create mode 100644 docs_src/header_param_models/tutorial002_pv1_an.py create mode 100644 docs_src/header_param_models/tutorial002_pv1_an_py310.py create mode 100644 docs_src/header_param_models/tutorial002_pv1_an_py39.py create mode 100644 docs_src/header_param_models/tutorial002_pv1_py310.py create mode 100644 docs_src/header_param_models/tutorial002_pv1_py39.py create mode 100644 docs_src/header_param_models/tutorial002_py310.py create mode 100644 docs_src/header_param_models/tutorial002_py39.py create mode 100644 docs_src/query_param_models/tutorial001.py create mode 100644 docs_src/query_param_models/tutorial001_an.py create mode 100644 docs_src/query_param_models/tutorial001_an_py310.py create mode 100644 docs_src/query_param_models/tutorial001_an_py39.py create mode 100644 docs_src/query_param_models/tutorial001_py310.py create mode 100644 docs_src/query_param_models/tutorial001_py39.py create mode 100644 docs_src/query_param_models/tutorial002.py create mode 100644 docs_src/query_param_models/tutorial002_an.py create mode 100644 docs_src/query_param_models/tutorial002_an_py310.py create mode 100644 docs_src/query_param_models/tutorial002_an_py39.py create mode 100644 docs_src/query_param_models/tutorial002_pv1.py create mode 100644 docs_src/query_param_models/tutorial002_pv1_an.py create mode 100644 docs_src/query_param_models/tutorial002_pv1_an_py310.py create mode 100644 docs_src/query_param_models/tutorial002_pv1_an_py39.py create mode 100644 docs_src/query_param_models/tutorial002_pv1_py310.py create mode 100644 docs_src/query_param_models/tutorial002_pv1_py39.py create mode 100644 docs_src/query_param_models/tutorial002_py310.py create mode 100644 docs_src/query_param_models/tutorial002_py39.py create mode 100644 scripts/playwright/cookie_param_models/image01.py create mode 100644 scripts/playwright/header_param_models/image01.py create mode 100644 scripts/playwright/query_param_models/image01.py create mode 100644 tests/test_tutorial/test_cookie_param_models/__init__.py create mode 100644 tests/test_tutorial/test_cookie_param_models/test_tutorial001.py create mode 100644 tests/test_tutorial/test_cookie_param_models/test_tutorial002.py create mode 100644 tests/test_tutorial/test_header_param_models/__init__.py create mode 100644 tests/test_tutorial/test_header_param_models/test_tutorial001.py create mode 100644 tests/test_tutorial/test_header_param_models/test_tutorial002.py create mode 100644 tests/test_tutorial/test_query_param_models/__init__.py create mode 100644 tests/test_tutorial/test_query_param_models/test_tutorial001.py create mode 100644 tests/test_tutorial/test_query_param_models/test_tutorial002.py diff --git a/docs/en/docs/img/tutorial/cookie-param-models/image01.png b/docs/en/docs/img/tutorial/cookie-param-models/image01.png new file mode 100644 index 0000000000000000000000000000000000000000..85c370f80a42e52768a412c066e686e4f2773ccd GIT binary patch literal 45217 zcmdqIcT|&G^eBjW)hh_xfPjFIYY>nw(z{A1Ql)pIfP~(A)vHJoklqQsL!^clniT0B zq(-_BNN6FnBm>^x@6EiKH}mG7_tsl)t*mvvb#lIac02pq?S#M5P@*JfA}1pwqkO3h z)+QsndHHyK^v~;;!!w}Dwaej}ySCB`vdZBHTV!N^lf48#*Y(NRS@bv6^(6N0k31P9 z8~#4z^6XUyMRqu&&o$b8^L(R}3fs3ywq^5a#*K}2jmKpUyB3HkzM8@Qr|J{J>ihqQ z75^cS5?+vP+Djn@{lhvX6$SkJpWNJsH-^!tKa`|42k`+Tn`+0s^H_X98+rN=$0ZtM zWWvw8ySqJ|cRbj5uJ9tuuKJto#?`}v>(}mIjX(eTv;Ar$3w=g*>uMDLt9Gz@5z3@?(*mGG5-}D zvUg~NGpe;o7(HFV%+~&U>i>@Gf8*^xUSF+zC;$JK-2aV0h|f2Z36uL%UnF@wl99q& z?Hhdz$?#S&*jPBugr;zAT zDa*E$)YB$@PfV7pP z+51HhfP_gBa;4n`nWI6fy3)h1QrEwJnDhTB=3js!zue+0zTLSlC@~F@zh8tR=NOm; zPH@aNU!7bs&rXmbmE9#Rby?m{fB>k&q$3eiIqlwP+ZKRWepa~^Co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7UOL2_3_mceb&a&G;%CwO`TIHa>%a(l@&*vtu6p3>=_}D@ zjr+`y$SH4imQV^>4i+|?&&7Jkk5hPPfOmLw%==;uti&2C!El9X^k-Nw7J zSghIg*HuQHQ^(_aKkz*c%`Q(RD#Qc>T zGpQYboPq5}k~Gy5M4^pIoc=`C93(GIr{rnhxj6|`adzG!6L)<)jw}0^XX4D$rcR2gFT!b(Nhl26-!|&T^Q_WWT)Mi@ByKLVw8fg~Jgu?JmvHvK>sy+-l&# z)`$`#+B7R8)k@dA^y`MPWa?FQFWon$&3cp@x_?ZCzmT&ZT@zV$x?7zm>)%A9!SSg1 zEJyw!#VXF^xa5(!VtG~h1qH%v9W`#tsiR1`MHO|;kODHxn vlA(&L8i`zQ6{%`DkNA)w<%j ../../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9-12 16" +{!> ../../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-13 17" +{!> ../../../docs_src/cookie_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7-10 14" +{!> ../../../docs_src/cookie_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9-12 16" +{!> ../../../docs_src/cookie_param_models/tutorial001.py!} +``` + +//// + +**FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined. + +## Check the Docs + +You can see the defined cookies in the docs UI at `/docs`: + +

          + +/// info + +Have in mind that, as **browsers handle cookies** in special ways and behind the scenes, they **don't** easily allow **JavaScript** to touch them. + +If you go to the **API docs UI** at `/docs` you will be able to see the **documentation** for cookies for your *path operations*. + +But even if you **fill the data** and click "Execute", because the docs UI works with **JavaScript**, the cookies won't be sent, and you will see an **error** message as if you didn't write any values. + +/// + +## Forbid Extra Cookies + +In some special use cases (probably not very common), you might want to **restrict** the cookies that you want to receive. + +Your API now has the power to control its own cookie consent. 🤪🍪 + +You can use Pydantic's model configuration to `forbid` any `extra` fields: + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/cookie_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_param_models/tutorial002.py!} +``` + +//// + +If a client tries to send some **extra cookies**, they will receive an **error** response. + +Poor cookie banners with all their effort to get your consent for the API to reject it. 🍪 + +For example, if the client tries to send a `santa_tracker` cookie with a value of `good-list-please`, the client will receive an **error** response telling them that the `santa_tracker` cookie is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Summary + +You can use **Pydantic models** to declare **cookies** in **FastAPI**. 😎 diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..8deb0a455 --- /dev/null +++ b/docs/en/docs/tutorial/header-param-models.md @@ -0,0 +1,184 @@ +# Header Parameter Models + +If you have a group of related **header parameters**, you can create a **Pydantic model** to declare them. + +This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎 + +/// note + +This is supported since FastAPI version `0.115.0`. 🤓 + +/// + +## Header Parameters with a Pydantic Model + +Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-14 18" +{!> ../../../docs_src/header_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9-14 18" +{!> ../../../docs_src/header_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-15 19" +{!> ../../../docs_src/header_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7-12 16" +{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9-14 18" +{!> ../../../docs_src/header_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7-12 16" +{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined. + +## Check the Docs + +You can see the required headers in the docs UI at `/docs`: + +
          + +
          + +## Forbid Extra Headers + +In some special use cases (probably not very common), you might want to **restrict** the headers that you want to receive. + +You can use Pydantic's model configuration to `forbid` any `extra` fields: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../../docs_src/header_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/header_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8" +{!> ../../../docs_src/header_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/header_param_models/tutorial002.py!} +``` + +//// + +If a client tries to send some **extra headers**, they will receive an **error** response. + +For example, if the client tries to send a `tool` header with a value of `plumbus`, they will receive an **error** response telling them that the header parameter `tool` is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Summary + +You can use **Pydantic models** to declare **headers** in **FastAPI**. 😎 diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..02e36dc0f --- /dev/null +++ b/docs/en/docs/tutorial/query-param-models.md @@ -0,0 +1,196 @@ +# Query Parameter Models + +If you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them. + +This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎 + +/// note + +This is supported since FastAPI version `0.115.0`. 🤓 + +/// + +## Query Parameters with a Pydantic Model + +Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-13 17" +{!> ../../../docs_src/query_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-12 16" +{!> ../../../docs_src/query_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-14 18" +{!> ../../../docs_src/query_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9-13 17" +{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8-12 16" +{!> ../../../docs_src/query_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9-13 17" +{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined. + +## Check the Docs + +You can see the query parameters in the docs UI at `/docs`: + +
          + +
          + +## Forbid Extra Query Parameters + +In some special use cases (probably not very common), you might want to **restrict** the query parameters that you want to receive. + +You can use Pydantic's model configuration to `forbid` any `extra` fields: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../../docs_src/query_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/query_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../../docs_src/query_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="10" +{!> ../../../docs_src/query_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/query_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="11" +{!> ../../../docs_src/query_param_models/tutorial002.py!} +``` + +//// + +If a client tries to send some **extra** data in the **query parameters**, they will receive an **error** response. + +For example, if the client tries to send a `tool` query parameter with a value of `plumbus`, like: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +They will receive an **error** response telling them that the query parameter `tool` is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Summary + +You can use **Pydantic models** to declare **query parameters** in **FastAPI**. 😎 + +/// tip + +Spoiler alert: you can also use Pydantic models to declare cookies and headers, but you will read about that later in the tutorial. 🤫 + +/// diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 7c810c2d7..5161b891b 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -118,6 +118,7 @@ nav: - tutorial/body.md - tutorial/query-params-str-validations.md - tutorial/path-params-numeric-validations.md + - tutorial/query-param-models.md - tutorial/body-multiple-params.md - tutorial/body-fields.md - tutorial/body-nested-models.md @@ -125,6 +126,8 @@ nav: - tutorial/extra-data-types.md - tutorial/cookie-params.md - tutorial/header-params.md + - tutorial/cookie-param-models.md + - tutorial/header-param-models.md - tutorial/response-model.md - tutorial/extra-models.md - tutorial/response-status-code.md diff --git a/docs_src/cookie_param_models/tutorial001.py b/docs_src/cookie_param_models/tutorial001.py new file mode 100644 index 000000000..cc65c43e1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001.py @@ -0,0 +1,17 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an.py b/docs_src/cookie_param_models/tutorial001_an.py new file mode 100644 index 000000000..e5839ffd5 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an.py @@ -0,0 +1,18 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py310.py b/docs_src/cookie_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..24cc889a9 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py310.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py39.py b/docs_src/cookie_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..3d90c2007 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_py310.py b/docs_src/cookie_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7cdee5a92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_py310.py @@ -0,0 +1,15 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002.py b/docs_src/cookie_param_models/tutorial002.py new file mode 100644 index 000000000..9679e890f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an.py b/docs_src/cookie_param_models/tutorial002_an.py new file mode 100644 index 000000000..ce5644b7b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py310.py b/docs_src/cookie_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..7fa70fe92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py39.py b/docs_src/cookie_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..a906ce6a1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1.py b/docs_src/cookie_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..13f78b850 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an.py b/docs_src/cookie_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..ddfda9b6f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..ac00360b6 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..573caea4b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..2c59aad12 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,18 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_py310.py b/docs_src/cookie_param_models/tutorial002_py310.py new file mode 100644 index 000000000..f011aa1af --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_py310.py @@ -0,0 +1,17 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/header_param_models/tutorial001.py b/docs_src/header_param_models/tutorial001.py new file mode 100644 index 000000000..4caaba87b --- /dev/null +++ b/docs_src/header_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_an.py b/docs_src/header_param_models/tutorial001_an.py new file mode 100644 index 000000000..b55c6b56b --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an.py @@ -0,0 +1,20 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py310.py b/docs_src/header_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..acfb6b9bf --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py39.py b/docs_src/header_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..51a5f94fc --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_py310.py b/docs_src/header_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7239c64ce --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_py39.py b/docs_src/header_param_models/tutorial001_py39.py new file mode 100644 index 000000000..4c1137813 --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py39.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002.py b/docs_src/header_param_models/tutorial002.py new file mode 100644 index 000000000..3f9aac58d --- /dev/null +++ b/docs_src/header_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_an.py b/docs_src/header_param_models/tutorial002_an.py new file mode 100644 index 000000000..771135d77 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py310.py b/docs_src/header_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..e9535f045 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py39.py b/docs_src/header_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..ca5208c9d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py39.py @@ -0,0 +1,21 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1.py b/docs_src/header_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..7e56cd993 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an.py b/docs_src/header_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..236778231 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an.py @@ -0,0 +1,23 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py310.py b/docs_src/header_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..e99e24ea5 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,22 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py39.py b/docs_src/header_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..18398b726 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,22 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py310.py b/docs_src/header_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..3dbff9d7b --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py39.py b/docs_src/header_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..86e19be0d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,22 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py310.py b/docs_src/header_param_models/tutorial002_py310.py new file mode 100644 index 000000000..3d2296345 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py310.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py39.py b/docs_src/header_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f8ce559a7 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py39.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/query_param_models/tutorial001.py b/docs_src/query_param_models/tutorial001.py new file mode 100644 index 000000000..0c0ab315e --- /dev/null +++ b/docs_src/query_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an.py b/docs_src/query_param_models/tutorial001_an.py new file mode 100644 index 000000000..28375057c --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py310.py b/docs_src/query_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..71427acae --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py310.py @@ -0,0 +1,18 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..ba690d3e3 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py310.py b/docs_src/query_param_models/tutorial001_py310.py new file mode 100644 index 000000000..3ebf9f4d7 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py310.py @@ -0,0 +1,18 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py new file mode 100644 index 000000000..54b52a054 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002.py b/docs_src/query_param_models/tutorial002.py new file mode 100644 index 000000000..1633bc464 --- /dev/null +++ b/docs_src/query_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an.py b/docs_src/query_param_models/tutorial002_an.py new file mode 100644 index 000000000..69705d4b4 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py310.py b/docs_src/query_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..975956502 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..2d4c1a62b --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1.py b/docs_src/query_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..71ccd961d --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an.py b/docs_src/query_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..1dd29157a --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py310.py b/docs_src/query_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..d635aae88 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py39.py b/docs_src/query_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..494fef11f --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py310.py b/docs_src/query_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..9ffdeefc0 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,21 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py39.py b/docs_src/query_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..7fa456a79 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py310.py b/docs_src/query_param_models/tutorial002_py310.py new file mode 100644 index 000000000..6ec418499 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py310.py @@ -0,0 +1,20 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f9bba028c --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 7548cf0c7..5cebbf00f 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -201,14 +201,23 @@ def get_flat_dependant( return flat_dependant +def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]: + if not fields: + return fields + first_field = fields[0] + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + return fields_to_extract + return fields + + 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 - ) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + return path_params + query_params + header_params + cookie_params def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: @@ -479,7 +488,15 @@ def analyze_param( field=field ), "Path params must be of one of the supported types" elif isinstance(field_info, params.Query): - assert is_scalar_field(field) or is_scalar_sequence_field(field) + assert ( + is_scalar_field(field) + or is_scalar_sequence_field(field) + or ( + lenient_issubclass(field.type_, BaseModel) + # For Pydantic v1 + and getattr(field, "shape", 1) == 1 + ) + ) return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) @@ -686,11 +703,14 @@ def _validate_value_with_model_field( return v_, [] -def _get_multidict_value(field: ModelField, values: Mapping[str, Any]) -> Any: +def _get_multidict_value( + field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None +) -> Any: + alias = alias or field.alias if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): - value = values.getlist(field.alias) + value = values.getlist(alias) else: - value = values.get(field.alias, None) + value = values.get(alias, None) if ( value is None or ( @@ -712,7 +732,55 @@ def request_params_to_args( received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[Any]]: values: Dict[str, Any] = {} - errors = [] + errors: List[Dict[str, Any]] = [] + + if not fields: + return values, errors + + first_field = fields[0] + fields_to_extract = fields + single_not_embedded_field = False + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + single_not_embedded_field = True + + params_to_process: Dict[str, Any] = {} + + processed_keys = set() + + for field in fields_to_extract: + alias = None + if isinstance(received_params, Headers): + # Handle fields extracted from a Pydantic Model for a header, each field + # doesn't have a FieldInfo of type Header with the default convert_underscores=True + convert_underscores = getattr(field.field_info, "convert_underscores", True) + if convert_underscores: + alias = ( + field.alias + if field.alias != field.name + else field.name.replace("_", "-") + ) + value = _get_multidict_value(field, received_params, alias=alias) + if value is not None: + params_to_process[field.name] = value + processed_keys.add(alias or field.alias) + processed_keys.add(field.name) + + for key, value in received_params.items(): + if key not in processed_keys: + params_to_process[key] = value + + if single_not_embedded_field: + field_info = first_field.field_info + assert isinstance( + field_info, params.Param + ), "Params must be subclasses of Param" + loc: Tuple[str, ...] = (field_info.in_.value,) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=params_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in fields: value = _get_multidict_value(field, received_params) field_info = field.field_info diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 79ad9f83f..947eca948 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -16,11 +16,15 @@ from fastapi._compat import ( ) from fastapi.datastructures import DefaultPlaceholder from fastapi.dependencies.models import Dependant -from fastapi.dependencies.utils import get_flat_dependant, get_flat_params +from fastapi.dependencies.utils import ( + _get_flat_fields_from_params, + get_flat_dependant, + get_flat_params, +) from fastapi.encoders import jsonable_encoder from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE from fastapi.openapi.models import OpenAPI -from fastapi.params import Body, Param +from fastapi.params import Body, ParamTypes from fastapi.responses import Response from fastapi.types import ModelNameMap from fastapi.utils import ( @@ -87,9 +91,9 @@ def get_openapi_security_definitions( return security_definitions, operation_security -def get_openapi_operation_parameters( +def _get_openapi_operation_parameters( *, - all_route_params: Sequence[ModelField], + dependant: Dependant, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ @@ -98,33 +102,47 @@ def get_openapi_operation_parameters( separate_input_output_schemas: bool = True, ) -> List[Dict[str, Any]]: parameters = [] - for param in all_route_params: - field_info = param.field_info - field_info = cast(Param, field_info) - if not field_info.include_in_schema: - continue - param_schema = get_schema_from_model_field( - field=param, - schema_generator=schema_generator, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - parameter = { - "name": param.alias, - "in": field_info.in_.value, - "required": param.required, - "schema": param_schema, - } - if field_info.description: - parameter["description"] = field_info.description - if field_info.openapi_examples: - parameter["examples"] = jsonable_encoder(field_info.openapi_examples) - elif field_info.example != Undefined: - parameter["example"] = jsonable_encoder(field_info.example) - if field_info.deprecated: - parameter["deprecated"] = True - parameters.append(parameter) + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + parameter_groups = [ + (ParamTypes.path, path_params), + (ParamTypes.query, query_params), + (ParamTypes.header, header_params), + (ParamTypes.cookie, cookie_params), + ] + for param_type, param_group in parameter_groups: + for param in param_group: + field_info = param.field_info + # field_info = cast(Param, field_info) + if not getattr(field_info, "include_in_schema", True): + continue + param_schema = get_schema_from_model_field( + field=param, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + parameter = { + "name": param.alias, + "in": param_type.value, + "required": param.required, + "schema": param_schema, + } + if field_info.description: + parameter["description"] = field_info.description + openapi_examples = getattr(field_info, "openapi_examples", None) + example = getattr(field_info, "example", None) + if openapi_examples: + parameter["examples"] = jsonable_encoder(openapi_examples) + elif example != Undefined: + parameter["example"] = jsonable_encoder(example) + if getattr(field_info, "deprecated", None): + parameter["deprecated"] = True + parameters.append(parameter) return parameters @@ -247,9 +265,8 @@ def get_openapi_path( operation.setdefault("security", []).extend(operation_security) if security_definitions: security_schemes.update(security_definitions) - all_route_params = get_flat_params(route.dependant) - operation_parameters = get_openapi_operation_parameters( - all_route_params=all_route_params, + operation_parameters = _get_openapi_operation_parameters( + dependant=route.dependant, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, @@ -379,6 +396,7 @@ def get_openapi_path( deep_dict_update(openapi_response, process_response) openapi_response["description"] = description http422 = str(HTTP_422_UNPROCESSABLE_ENTITY) + all_route_params = get_flat_params(route.dependant) if (all_route_params or route.body_field) and not any( status in operation["responses"] for status in [http422, "4XX", "default"] diff --git a/scripts/playwright/cookie_param_models/image01.py b/scripts/playwright/cookie_param_models/image01.py new file mode 100644 index 000000000..77c91bfe2 --- /dev/null +++ b/scripts/playwright/cookie_param_models/image01.py @@ -0,0 +1,39 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("link", name="/items/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/header_param_models/image01.py b/scripts/playwright/header_param_models/image01.py new file mode 100644 index 000000000..53914251e --- /dev/null +++ b/scripts/playwright/header_param_models/image01.py @@ -0,0 +1,38 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/header_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/query_param_models/image01.py b/scripts/playwright/query_param_models/image01.py new file mode 100644 index 000000000..0ea1d0df4 --- /dev/null +++ b/scripts/playwright/query_param_models/image01.py @@ -0,0 +1,41 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + page.get_by_role("heading", name="Servers").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/query_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_tutorial/test_cookie_param_models/__init__.py b/tests/test_tutorial/test_cookie_param_models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py new file mode 100644 index 000000000..60643185a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py @@ -0,0 +1,205 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == snapshot( + {"session_id": "123", "fatebook_tracker": None, "googall_tracker": None} + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py new file mode 100644 index 000000000..30adadc8a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py @@ -0,0 +1,233 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "extra"], + "msg": "Extra inputs are not permitted", + "input": "track-me-here-too", + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.extra", + "loc": ["cookie", "extra"], + "msg": "extra fields not permitted", + } + ] + } + ) + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_header_param_models/__init__.py b/tests/test_tutorial/test_header_param_models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py new file mode 100644 index 000000000..06b2404cf --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py @@ -0,0 +1,238 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "x_tag": [], + "host": "testserver", + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py new file mode 100644 index 000000000..e07655a0c --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py @@ -0,0 +1,249 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + client.headers.clear() + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200, response.text + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": {"x_tag": [], "host": "testserver"}, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["header", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_param_models/__init__.py b/tests/test_tutorial/test_query_param_models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py new file mode 100644 index 000000000..5b7bc7b42 --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py @@ -0,0 +1,260 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py new file mode 100644 index 000000000..4432c9d8a --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py @@ -0,0 +1,282 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["query", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) From 7eadeb69bdc579f7de92d0e7762a7825a5da192a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Sep 2024 18:54:35 +0000 Subject: [PATCH 270/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d6d2a05b3..405d70c37 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Features + +* ✨ Add support for Pydantic models for parameters using `Query`, `Cookie`, `Header`. PR [#12199](https://github.com/fastapi/fastapi/pull/12199) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12195](https://github.com/fastapi/fastapi/pull/12195) by [@ceb10n](https://github.com/ceb10n). From b36047b54ae4f965d03426872dbc1fa1f32c746b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 17 Sep 2024 21:06:26 +0200 Subject: [PATCH 271/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 120 ++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 405d70c37..722bc5008 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,126 @@ hide: ## Latest Changes +### Highlights + +Now you can declare `Query`, `Header`, and `Cookie` parameters with Pydantic models. 🎉 + +#### `Query` Parameter Models + +Use Pydantic models for `Query` parameters: + +```python +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query +``` + +Read the new docs: [Query Parameter Models](https://fastapi.tiangolo.com/tutorial/query-param-models/). + +#### `Header` Parameter Models + +Use Pydantic models for `Header` parameters: + +```python +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers +``` + +Read the new docs: [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/). + +#### `Cookie` Parameter Models + +Use Pydantic models for `Cookie` parameters: + +```python +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies +``` + +Read the new docs: [Cookie Parameter Models](https://fastapi.tiangolo.com/tutorial/cookie-param-models/). + +#### Forbid Extra Query (Cookie, Header) Parameters + +Use Pydantic models to restrict extra values for `Query` parameters (also applies to `Header` and `Cookie` parameters). + +To achieve it, use Pydantic's `model_config = {"extra": "forbid"}`: + +```python +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query +``` + +This applies to `Query`, `Header`, and `Cookie` parameters, read the new docs: + +* [Forbid Extra Query Parameters](https://fastapi.tiangolo.com/tutorial/query-param-models/#forbid-extra-query-parameters) +* [Forbid Extra Headers](https://fastapi.tiangolo.com/tutorial/header-param-models/#forbid-extra-headers) +* [Forbid Extra Cookies](https://fastapi.tiangolo.com/tutorial/cookie-param-models/#forbid-extra-cookies) + ### Features * ✨ Add support for Pydantic models for parameters using `Query`, `Cookie`, `Header`. PR [#12199](https://github.com/fastapi/fastapi/pull/12199) by [@tiangolo](https://github.com/tiangolo). From 40e33e492dbf4af6172997f4e3238a32e56cbe26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 17 Sep 2024 21:07:35 +0200 Subject: [PATCH 272/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 722bc5008..ea7ac9215 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.0 + ### Highlights Now you can declare `Query`, `Header`, and `Cookie` parameters with Pydantic models. 🎉 diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 3925d3603..7dd74c28f 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.114.2" +__version__ = "0.115.0" from starlette import status as status From 42e0e368bca7bf94f425c4bd2eca0b4ac4b5cab0 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Wed, 18 Sep 2024 18:09:57 +0200 Subject: [PATCH 273/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20small=20typos=20in?= =?UTF-8?q?=20the=20documentation=20(#12213)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/additional-responses.md | 2 +- docs/en/docs/advanced/async-tests.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 2 +- docs/en/docs/advanced/custom-response.md | 6 +++--- docs/en/docs/advanced/middleware.md | 4 ++-- .../docs/advanced/path-operation-advanced-configuration.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/advanced/security/http-basic-auth.md | 2 +- docs/en/docs/advanced/security/oauth2-scopes.md | 2 +- docs/en/docs/advanced/settings.md | 2 +- docs/en/docs/deployment/concepts.md | 2 +- docs/en/docs/deployment/docker.md | 2 +- docs/en/docs/deployment/server-workers.md | 2 +- docs/en/docs/release-notes.md | 2 +- 14 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 674f0672c..4fec41213 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -18,7 +18,7 @@ But for those additional responses you have to make sure you return a `Response` You can pass to your *path operation decorators* a parameter `responses`. -It receives a `dict`, the keys are status codes for each response, like `200`, and the values are other `dict`s with the information for each of them. +It receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them. Each of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`. diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index 580d9142c..a528c80fe 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -102,6 +102,6 @@ As the testing function is now asynchronous, you can now also call (and `await`) /// tip -If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using
          MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. +If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient), remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. /// diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 5ff64016c..e642b1910 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -303,7 +303,7 @@ This is a more advanced use case. Feel free to skip it. By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`. -But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with a staging and production environments. +But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment. If you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a "server" with this `root_path` at the beginning of the list. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 79f755815..1cefe979f 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -142,7 +142,7 @@ It accepts the following parameters: * `headers` - A `dict` of strings. * `media_type` - A `str` giving the media type. E.g. `"text/html"`. -FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types. +FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. ```Python hl_lines="1 18" {!../../../docs_src/response_directly/tutorial002.py!} @@ -154,7 +154,7 @@ Takes some text or bytes and returns an HTML response, as you read above. ### `PlainTextResponse` -Takes some text or bytes and returns an plain text response. +Takes some text or bytes and returns a plain text response. ```Python hl_lines="2 7 9" {!../../../docs_src/custom_response/tutorial005.py!} @@ -273,7 +273,7 @@ Asynchronously streams a file as the response. Takes a different set of arguments to instantiate than the other response types: -* `path` - The filepath to the file to stream. +* `path` - The file path to the file to stream. * `headers` - Any custom headers to include, as a dictionary. * `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type. * `filename` - If set, this will be included in the response `Content-Disposition`. diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 70415adca..ab7778db0 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -24,7 +24,7 @@ app = SomeASGIApp() new_app = UnicornMiddleware(app, some_config="rainbow") ``` -But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares to handle server errors and custom exception handlers work properly. +But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly. For that, you use `app.add_middleware()` (as in the example for CORS). @@ -55,7 +55,7 @@ For the next examples, you could also use `from starlette.middleware.something i Enforces that all incoming requests must either be `https` or `wss`. -Any incoming requests to `http` or `ws` will be redirected to the secure scheme instead. +Any incoming request to `http` or `ws` will be redirected to the secure scheme instead. ```Python hl_lines="2 6" {!../../../docs_src/advanced_middleware/tutorial001.py!} diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index c8874bad9..d599006d2 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -149,7 +149,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: -```Python hl_lines="20-37 39-40" +```Python hl_lines="19-36 39-40" {!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 2251659c5..092aeceb1 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -28,7 +28,7 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure its contents are ready for it. +Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index c302bf8dc..e669d10d8 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -144,7 +144,7 @@ And then they can try again knowing that it's probably something more similar to #### A "professional" attack -Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time. +Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time. But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index ff52d7bb8..fdd8db7b9 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -769,7 +769,7 @@ But if you are building an OAuth2 application that others would connect to (i.e. The most common is the implicit flow. -The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. +The most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. /// note diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 22bf7de20..8c04d2507 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -374,7 +374,7 @@ Prefer to use the `Annotated` version if possible. //// -Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. +Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. #### `lru_cache` Technical Details diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 69ee71a73..e71a7487a 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -257,7 +257,7 @@ But in most cases, you will want to perform these steps only **once**. So, you will want to have a **single process** to perform those **previous steps**, before starting the application. -And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it on **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. +And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it in **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 2d832a238..b106f7ac3 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -615,6 +615,6 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai * Memory * Previous steps before starting -In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. +In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 5e369e071..622c10a30 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -139,7 +139,7 @@ From the list of deployment concepts from above, using workers would mainly help ## Containers and Docker -In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. +In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll explain some strategies you could use to handle the other **deployment concepts**. I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ea7ac9215..5e8815e65 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -494,7 +494,7 @@ Discussed here: [#11522](https://github.com/fastapi/fastapi/pull/11522) and here ### Upgrades * ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). - * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they not included in `pip install fastapi`. + * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they are not included in `pip install fastapi`. * 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). ### Docs From 4d6cab3ec619ee1186b975f9520d1f396010f9a4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 18 Sep 2024 16:10:21 +0000 Subject: [PATCH 274/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5e8815e65..0411bbdda 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). + ## 0.115.0 ### Highlights From 6cc24416e22845ef8d188e94993a6285afaf255d Mon Sep 17 00:00:00 2001 From: Albert Villanova del Moral <8515462+albertvillanova@users.noreply.github.com> Date: Thu, 19 Sep 2024 11:47:28 +0200 Subject: [PATCH 275/356] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20docstring=20?= =?UTF-8?q?typos=20in=20http=20security=20(#12223)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix docstring typos in http security --- fastapi/security/http.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/security/http.py b/fastapi/security/http.py index a142b135d..e06f3d66d 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -277,7 +277,7 @@ class HTTPBearer(HTTPBase): bool, Doc( """ - By default, if the HTTP Bearer token not provided (in an + By default, if the HTTP Bearer token is not provided (in an `Authorization` header), `HTTPBearer` will automatically cancel the request and send the client an error. @@ -380,7 +380,7 @@ class HTTPDigest(HTTPBase): bool, Doc( """ - By default, if the HTTP Digest not provided, `HTTPDigest` will + By default, if the HTTP Digest is not provided, `HTTPDigest` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Digest is not From 7c6f2f8fde68f488163376c9e92a59d46c491298 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 19 Sep 2024 09:47:54 +0000 Subject: [PATCH 276/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0411bbdda..a8566ceaa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). +### Internal + +* ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). + ## 0.115.0 ### Highlights From 97ac2286aaa9be8289b43f23cf8e8ddd3356aadb Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 20 Sep 2024 08:00:08 -0300 Subject: [PATCH 277/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/configure-swagger-ui.md`=20?= =?UTF-8?q?(#12222)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/configure-swagger-ui.md | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/pt/docs/how-to/configure-swagger-ui.md diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..b40dad695 --- /dev/null +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# Configurar Swagger UI + +Você pode configurar alguns parâmetros extras da UI do Swagger. + +Para configurá-los, passe o argumento `swagger_ui_parameters` ao criar o objeto de aplicativo `FastAPI()` ou para a função `get_swagger_ui_html()`. + +`swagger_ui_parameters` recebe um dicionário com as configurações passadas diretamente para o Swagger UI. + +O FastAPI converte as configurações para **JSON** para torná-las compatíveis com JavaScript, pois é disso que o Swagger UI precisa. + +## Desabilitar realce de sintaxe + +Por exemplo, você pode desabilitar o destaque de sintaxe na UI do Swagger. + +Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: + + + +Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...e então o Swagger UI não mostrará mais o destaque de sintaxe: + + + +## Alterar o tema + +Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +Essa configuração alteraria o tema de cores de destaque de sintaxe: + + + +## Alterar parâmetros de UI padrão do Swagger + +O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a maioria dos casos de uso. + +Inclui estas configurações padrão: + +```Python +{!../../../fastapi/openapi/docs.py[ln:7-23]!} +``` + +Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. + +Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## Outros parâmetros da UI do Swagger + +Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. + +## Configurações somente JavaScript + +A interface do usuário do Swagger também permite que outras configurações sejam objetos **somente JavaScript** (por exemplo, funções JavaScript). + +O FastAPI também inclui estas configurações de `predefinições` somente para JavaScript: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Esses são objetos **JavaScript**, não strings, então você não pode passá-los diretamente do código Python. + +Se você precisar usar configurações somente JavaScript como essas, você pode usar um dos métodos acima. Sobrescreva todas as *operações de rotas* do Swagger UI e escreva manualmente qualquer JavaScript que você precisar. From cf93157be74bc4a8d90846938b5ca2dab1ef60b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Sep 2024 11:00:31 +0000 Subject: [PATCH 278/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a8566ceaa..79fbdf1b8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). +### Translations + +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus). + ### Internal * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). From 0b1da2d9101d1bceefb62f77be83debc450135ec Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 20 Sep 2024 08:01:03 -0300 Subject: [PATCH 279/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/deployment/server-workers.md`=20(#?= =?UTF-8?q?12220)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/server-workers.md | 152 ++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 docs/pt/docs/deployment/server-workers.md diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md new file mode 100644 index 000000000..0d6cd5b39 --- /dev/null +++ b/docs/pt/docs/deployment/server-workers.md @@ -0,0 +1,152 @@ +# Trabalhadores do Servidor - Uvicorn com Trabalhadores + +Vamos rever os conceitos de implantação anteriores: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* **Replicação (o número de processos em execução)** +* Memória +* Etapas anteriores antes de iniciar + +Até este ponto, com todos os tutoriais nos documentos, você provavelmente estava executando um **programa de servidor**, por exemplo, usando o comando `fastapi`, que executa o Uvicorn, executando um **único processo**. + +Ao implantar aplicativos, você provavelmente desejará ter alguma **replicação de processos** para aproveitar **vários núcleos** e poder lidar com mais solicitações. + +Como você viu no capítulo anterior sobre [Conceitos de implantação](concepts.md){.internal-link target=_blank}, há várias estratégias que você pode usar. + +Aqui mostrarei como usar o **Uvicorn** com **processos de trabalho** usando o comando `fastapi` ou o comando `uvicorn` diretamente. + +/// info | "Informação" + +Se você estiver usando contêineres, por exemplo com Docker ou Kubernetes, falarei mais sobre isso no próximo capítulo: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +Em particular, ao executar no **Kubernetes** você provavelmente **não** vai querer usar vários trabalhadores e, em vez disso, executar **um único processo Uvicorn por contêiner**, mas falarei sobre isso mais adiante neste capítulo. + +/// + +## Vários trabalhadores + +Você pode iniciar vários trabalhadores com a opção de linha de comando `--workers`: + +//// tab | `fastapi` + +Se você usar o comando `fastapi`: + +
          + +```console +$
           fastapi run --workers 4 main.py
          +INFO     Using path main.py
          +INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
          +INFO     Searching for package file structure from directories with __init__.py files
          +INFO     Importing from /home/user/code/awesomeapp
          +
          + ╭─ Python module file ─╮
          + │                      │
          + │  🐍 main.py          │
          + │                      │
          + ╰──────────────────────╯
          +
          +INFO     Importing module main
          +INFO     Found importable FastAPI app
          +
          + ╭─ Importable FastAPI app ─╮
          + │                          │
          + │  from main import app    │
          + │                          │
          + ╰──────────────────────────╯
          +
          +INFO     Using import string main:app
          +
          + ╭─────────── FastAPI CLI - Production mode ───────────╮
          + │                                                     │
          + │  Serving at: http://0.0.0.0:8000                    │
          + │                                                     │
          + │  API docs: http://0.0.0.0:8000/docs                 │
          + │                                                     │
          + │  Running in production mode, for development use:   │
          + │                                                     │
          + fastapi dev
          + │                                                     │
          + ╰─────────────────────────────────────────────────────╯
          +
          +INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
          +INFO:     Started parent process [27365]
          +INFO:     Started server process [27368]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27369]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27370]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +INFO:     Started server process [27367]
          +INFO:     Waiting for application startup.
          +INFO:     Application startup complete.
          +
          +``` + +
          + +//// + +//// tab | `uvicorn` + +Se você preferir usar o comando `uvicorn` diretamente: + +
          + +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
          + +//// + +A única opção nova aqui é `--workers` informando ao Uvicorn para iniciar 4 processos de trabalho. + +Você também pode ver que ele mostra o **PID** de cada processo, `27365` para o processo pai (este é o **gerenciador de processos**) e um para cada processo de trabalho: `27368`, `27369`, `27370` e `27367`. + +## Conceitos de Implantação + +Aqui você viu como usar vários **trabalhadores** para **paralelizar** a execução do aplicativo, aproveitar **vários núcleos** na CPU e conseguir atender **mais solicitações**. + +Da lista de conceitos de implantação acima, o uso de trabalhadores ajudaria principalmente com a parte da **replicação** e um pouco com as **reinicializações**, mas você ainda precisa cuidar dos outros: + +* **Segurança - HTTPS** +* **Executando na inicialização** +* ***Reinicializações*** +* Replicação (o número de processos em execução) +* **Memória** +* **Etapas anteriores antes de iniciar** + +## Contêineres e Docker + +No próximo capítulo sobre [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}, explicarei algumas estratégias que você pode usar para lidar com os outros **conceitos de implantação**. + +Vou mostrar como **construir sua própria imagem do zero** para executar um único processo Uvicorn. É um processo simples e provavelmente é o que você gostaria de fazer ao usar um sistema de gerenciamento de contêineres distribuídos como o **Kubernetes**. + +## Recapitular + +Você pode usar vários processos de trabalho com a opção CLI `--workers` com os comandos `fastapi` ou `uvicorn` para aproveitar as vantagens de **CPUs multi-core** e executar **vários processos em paralelo**. + +Você pode usar essas ferramentas e ideias se estiver configurando **seu próprio sistema de implantação** enquanto cuida dos outros conceitos de implantação. + +Confira o próximo capítulo para aprender sobre **FastAPI** com contêineres (por exemplo, Docker e Kubernetes). Você verá que essas ferramentas têm maneiras simples de resolver os outros **conceitos de implantação** também. ✨ From 4e3db0b6890277149cf87553bf6967c992cdb392 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Sep 2024 11:03:12 +0000 Subject: [PATCH 280/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 79fbdf1b8..161eef6ae 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus). ### Internal From b1024e73bebcda280839989e4d0461f46de1096e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Gustavo=20Rogel=20de=20Oliveira?= Date: Fri, 20 Sep 2024 08:10:02 -0300 Subject: [PATCH 281/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/deployment/manually.md`=20(#12210)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/manually.md | 169 ++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 docs/pt/docs/deployment/manually.md diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md new file mode 100644 index 000000000..9eff3daaa --- /dev/null +++ b/docs/pt/docs/deployment/manually.md @@ -0,0 +1,169 @@ +# Execute um Servidor Manualmente + +## Utilize o comando `fastapi run` + +Em resumo, utilize o comando `fastapi run` para inicializar sua aplicação FastAPI: + +
          + +```console +$ fastapi run main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + fastapi dev + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Started server process [2306215] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +``` + +
          + +Isto deve funcionar para a maioria dos casos. 😎 + +Você pode utilizar esse comando, por exemplo, para iniciar sua aplicação **FastAPI** em um contêiner, em um servidor, etc. + +## Servidores ASGI + +Vamos nos aprofundar um pouco mais em detalhes. + +FastAPI utiliza um padrão para construir frameworks e servidores web em Python chamado ASGI. FastAPI é um framework web ASGI. + +A principal coisa que você precisa para executar uma aplicação **FastAPI** (ou qualquer outra aplicação ASGI) em uma máquina de servidor remoto é um programa de servidor ASGI como o **Uvicorn**, que é o que vem por padrão no comando `fastapi`. + +Existem diversas alternativas, incluindo: + +* Uvicorn: um servidor ASGI de alta performance. +* Hypercorn: um servidor ASGI compátivel com HTTP/2, Trio e outros recursos. +* Daphne: servidor ASGI construído para Django Channels. +* Granian: um servidor HTTP Rust para aplicações Python. +* NGINX Unit: NGINX Unit é um runtime de aplicação web leve e versátil. + +## Máquina Servidora e Programa Servidor + +Existe um pequeno detalhe sobre estes nomes para se manter em mente. 💡 + +A palavra "**servidor**" é comumente usada para se referir tanto ao computador remoto/nuvem (a máquina física ou virtual) quanto ao programa que está sendo executado nessa máquina (por exemplo, Uvicorn). + +Apenas tenha em mente que quando você ler "servidor" em geral, isso pode se referir a uma dessas duas coisas. + +Quando se refere à máquina remota, é comum chamá-la de **servidor**, mas também de **máquina**, **VM** (máquina virtual), **nó**. Todos esses termos se referem a algum tipo de máquina remota, normalmente executando Linux, onde você executa programas. + +## Instale o Programa Servidor + +Quando você instala o FastAPI, ele vem com um servidor de produção, o Uvicorn, e você pode iniciá-lo com o comando `fastapi run`. + +Mas você também pode instalar um servidor ASGI manualmente. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, você pode instalar a aplicação do servidor. + +Por exemplo, para instalar o Uvicorn: + +
          + +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
          + +Um processo semelhante se aplicaria a qualquer outro programa de servidor ASGI. + +/// tip | "Dica" + +Adicionando o `standard`, o Uvicorn instalará e usará algumas dependências extras recomendadas. + +Isso inclui o `uvloop`, a substituição de alto desempenho para `asyncio`, que fornece um grande aumento de desempenho de concorrência. + +Quando você instala o FastAPI com algo como `pip install "fastapi[standard]"`, você já obtém `uvicorn[standard]` também. + +/// + +## Execute o Programa Servidor + +Se você instalou um servidor ASGI manualmente, normalmente precisará passar uma string de importação em um formato especial para que ele importe sua aplicação FastAPI: + +
          + +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +
          + +/// note | "Nota" + +O comando `uvicorn main:app` refere-se a: + +* `main`: o arquivo `main.py` (o "módulo" Python). +* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`. + +É equivalente a: + +```Python +from main import app +``` + +/// + +Cada programa de servidor ASGI alternativo teria um comando semelhante, você pode ler mais na documentação respectiva. + +/// warning | "Aviso" + +Uvicorn e outros servidores suportam a opção `--reload` que é útil durante o desenvolvimento. + +A opção `--reload` consome muito mais recursos, é mais instável, etc. + +Ela ajuda muito durante o **desenvolvimento**, mas você **não deve** usá-la em **produção**. + +/// + +## Conceitos de Implantação + +Esses exemplos executam o programa do servidor (por exemplo, Uvicorn), iniciando **um único processo**, ouvindo em todos os IPs (`0.0.0.0`) em uma porta predefinida (por exemplo, `80`). + +Esta é a ideia básica. Mas você provavelmente vai querer cuidar de algumas coisas adicionais, como: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Passos anteriores antes de começar + +Vou te contar mais sobre cada um desses conceitos, como pensar sobre eles e alguns exemplos concretos com estratégias para lidar com eles nos próximos capítulos. 🚀 From 2459a009f43b96dc86e04e94d2a996983626ffce Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Sep 2024 11:11:21 +0000 Subject: [PATCH 282/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 161eef6ae..9e44bbf45 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus). From 6aefc316008fa920a93493b6f458b1fe3b5c1324 Mon Sep 17 00:00:00 2001 From: Max Scheijen <47034840+maxscheijen@users.noreply.github.com> Date: Fri, 20 Sep 2024 13:13:32 +0200 Subject: [PATCH 283/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Dutch=20translatio?= =?UTF-8?q?n=20for=20`docs/nl/docs/environment-variables.md`=20(#12200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/nl/docs/environment-variables.md | 298 ++++++++++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 docs/nl/docs/environment-variables.md diff --git a/docs/nl/docs/environment-variables.md b/docs/nl/docs/environment-variables.md new file mode 100644 index 000000000..f6b3d285b --- /dev/null +++ b/docs/nl/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Omgevingsvariabelen + +/// tip + +Als je al weet wat "omgevingsvariabelen" zijn en hoe je ze kunt gebruiken, kun je deze stap gerust overslaan. + +/// + +Een omgevingsvariabele (ook bekend als "**env var**") is een variabele die **buiten** de Python-code leeft, in het **besturingssysteem** en die door je Python-code (of door andere programma's) kan worden gelezen. + +Omgevingsvariabelen kunnen nuttig zijn voor het bijhouden van applicatie **instellingen**, als onderdeel van de **installatie** van Python, enz. + +## Omgevingsvariabelen maken en gebruiken + +Je kunt omgevingsvariabelen **maken** en gebruiken in de **shell (terminal)**, zonder dat je Python nodig hebt: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Je zou een omgevingsvariabele MY_NAME kunnen maken met +$ export MY_NAME="Wade Wilson" + +// Dan zou je deze met andere programma's kunnen gebruiken, zoals +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Maak een omgevingsvariabel MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Gebruik het met andere programma's, zoals +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +## Omgevingsvariabelen uitlezen in Python + +Je kunt omgevingsvariabelen **buiten** Python aanmaken, in de terminal (of met een andere methode) en ze vervolgens **in Python uitlezen**. + +Je kunt bijvoorbeeld een bestand `main.py` hebben met: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Het tweede argument van `os.getenv()` is de standaardwaarde die wordt geretourneerd. + +Als je dit niet meegeeft, is de standaardwaarde `None`. In dit geval gebruiken we standaard `"World"`. + +/// + +Dan zou je dat Python-programma kunnen aanroepen: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ export MY_NAME="Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ $Env:MY_NAME = "Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
          + +//// + +Omdat omgevingsvariabelen buiten de code kunnen worden ingesteld, maar wel door de code kunnen worden gelezen en niet hoeven te worden opgeslagen (gecommit naar `git`) met de rest van de bestanden, worden ze vaak gebruikt voor configuraties of **instellingen**. + +Je kunt ook een omgevingsvariabele maken die alleen voor een **specifieke programma-aanroep** beschikbaar is, die alleen voor dat programma beschikbaar is en alleen voor de duur van dat programma. + +Om dat te doen, maak je het vlak voor het programma zelf aan, op dezelfde regel: + +
          + +```console +// Maak een omgevingsvariabele MY_NAME in de regel voor deze programma-aanroep +$ MY_NAME="Wade Wilson" python main.py + +// Nu kan het de omgevingsvariabele lezen + +Hello Wade Wilson from Python + +// De omgevingsvariabelen bestaan daarna niet meer +$ python main.py + +Hello World from Python +``` + +
          + +/// tip + +Je kunt er meer over lezen op The Twelve-Factor App: Config. + +/// + +## Types en Validatie + +Deze omgevingsvariabelen kunnen alleen **tekstuele gegevens** verwerken, omdat ze extern zijn aan Python, compatibel moeten zijn met andere programma's en de rest van het systeem (zelfs met verschillende besturingssystemen, zoals Linux, Windows en macOS). + +Dat betekent dat **elke waarde** die in Python uit een omgevingsvariabele wordt gelezen **een `str` zal zijn** en dat elke conversie naar een ander type of elke validatie in de code moet worden uitgevoerd. + +Meer informatie over het gebruik van omgevingsvariabelen voor het verwerken van **applicatie instellingen** vind je in de [Geavanceerde gebruikershandleiding - Instellingen en Omgevingsvariabelen](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Omgevingsvariabele + +Er is een **speciale** omgevingsvariabele met de naam **`PATH`**, die door de besturingssystemen (Linux, macOS, Windows) wordt gebruikt om programma's te vinden die uitgevoerd kunnen worden. + +De waarde van de variabele `PATH` is een lange string die bestaat uit mappen die gescheiden worden door een dubbele punt `:` op Linux en macOS en door een puntkomma `;` op Windows. + +De omgevingsvariabele `PATH` zou er bijvoorbeeld zo uit kunnen zien: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Wanneer je een **opdracht** in de terminal typt, **zoekt** het besturingssysteem naar het programma in **elk van de mappen** die vermeld staan in de omgevingsvariabele `PATH`. + +Wanneer je bijvoorbeeld `python` in de terminal typt, zoekt het besturingssysteem naar een programma met de naam `python` in de **eerste map** in die lijst. + +Zodra het gevonden wordt, zal het dat programma **gebruiken**. Anders blijft het in de **andere mappen** zoeken. + +### Python installeren en `PATH` bijwerken + +Wanneer je Python installeert, word je mogelijk gevraagd of je de omgevingsvariabele `PATH` wilt bijwerken. + +//// tab | Linux, macOS + +Stel dat je Python installeert en het komt terecht in de map `/opt/custompython/bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `/opt/custompython/bin` toevoegen aan de `PATH` omgevingsvariabele. + +Dit zou er zo uit kunnen zien: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `/opt/custompython/bin` (de laatste map) vinden en dat gebruiken. + +//// + +//// tab | Windows + +Stel dat je Python installeert en het komt terecht in de map `C:\opt\custompython\bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `C:\opt\custompython\bin` toevoegen aan de `PATH` omgevingsvariabele. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `C:\opt\custompython\bin` (de laatste map) vinden en dat gebruiken. + +//// + +Dus als je typt: + +
          + +```console +$ python +``` + +
          + +//// tab | Linux, macOS + +Zal het systeem het `python`-programma in `/opt/custompython/bin` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
          + +```console +$ /opt/custompython/bin/python +``` + +
          + +//// + +//// tab | Windows + +Zal het systeem het `python`-programma in `C:\opt\custompython\bin\python` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
          + +```console +$ C:\opt\custompython\bin\python +``` + +
          + +//// + +Deze informatie is handig wanneer je meer wilt weten over [virtuele omgevingen](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +Hiermee heb je basiskennis van wat **omgevingsvariabelen** zijn en hoe je ze in Python kunt gebruiken. + +Je kunt er ook meer over lezen op de Wikipedia over omgevingsvariabelen. + +In veel gevallen is het niet direct duidelijk hoe omgevingsvariabelen nuttig zijn en hoe je ze moet toepassen. Maar ze blijven in veel verschillende scenario's opduiken als je aan het ontwikkelen bent, dus het is goed om er meer over te weten. + +Je hebt deze informatie bijvoorbeeld nodig in de volgende sectie, over [Virtuele Omgevingen](virtual-environments.md). From 13e20228a92acadac0175ec61a7dd50c695708b0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Sep 2024 11:15:35 +0000 Subject: [PATCH 284/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9e44bbf45..30d9280a3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus). From 2cdf111e61a6ef8499be8722f2a036f3cd82b46a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20S=C3=A1nchez=20Castro?= <72013291+JavierSanchezCastro@users.noreply.github.com> Date: Fri, 20 Sep 2024 13:34:07 +0200 Subject: [PATCH 285/356] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/es/docs/python-types.md`=20(#12235)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/python-types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 4015dbb05..c873385bc 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -46,7 +46,7 @@ La función hace lo siguiente: Es un programa muy simple. -Ahora, imagina que lo estás escribiendo desde ceros. +Ahora, imagina que lo estás escribiendo desde cero. En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos... From f6dfb832c59c1bdacbad6dc2ee7bb97d08381339 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Sep 2024 11:34:29 +0000 Subject: [PATCH 286/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 30d9280a3..3ca428393 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). * 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus). From 6a2ad7031cb8e073fc11b3349816a8f48fca1864 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Sat, 21 Sep 2024 18:37:48 -0300 Subject: [PATCH 287/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/deployment/cloud.md`=20(#12217)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/pt/docs/deployment/cloud.md diff --git a/docs/pt/docs/deployment/cloud.md b/docs/pt/docs/deployment/cloud.md new file mode 100644 index 000000000..e6522f50f --- /dev/null +++ b/docs/pt/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Implantar FastAPI em provedores de nuvem + +Você pode usar praticamente **qualquer provedor de nuvem** para implantar seu aplicativo FastAPI. + +Na maioria dos casos, os principais provedores de nuvem têm guias para implantar o FastAPI com eles. + +## Provedores de Nuvem - Patrocinadores + +Alguns provedores de nuvem ✨ [**patrocinam o FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, o que garante o **desenvolvimento** contínuo e saudável do FastAPI e seu **ecossistema**. + +E isso mostra seu verdadeiro comprometimento com o FastAPI e sua **comunidade** (você), pois eles não querem apenas fornecer a você um **bom serviço**, mas também querem ter certeza de que você tenha uma **estrutura boa e saudável**, o FastAPI. 🙇 + +Talvez você queira experimentar os serviços deles e seguir os guias: + +* Platform.sh +* Porter +* Coherence From 9606b916ef7c883f5ebeac1bf3db9adf5ae646a9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 21 Sep 2024 21:38:11 +0000 Subject: [PATCH 288/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3ca428393..c345b6045 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). * ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). * 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel). From d9e989e274e9224c20f1847c2110896c2a4cc23d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 24 Sep 2024 12:14:00 +0200 Subject: [PATCH 289/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12253)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.5 → v0.6.7](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.5...v0.6.7) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4b1b10a68..1502f0abd 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.5 + rev: v0.6.7 hooks: - id: ruff args: From 10f3cb5ab1d5e2848146b85256df056c1bcc9753 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 24 Sep 2024 10:14:28 +0000 Subject: [PATCH 290/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c345b6045..8a6f2d8be 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). ## 0.115.0 From bb018fc46cac48fd51675dfbbeb8d9b3b204fdc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 26 Sep 2024 19:17:21 +0200 Subject: [PATCH 291/356] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Fine.dev=20(#12271)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index 3b01b713a..f274265de 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,6 @@ The key features are: - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index d96646fb3..6db9c509a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -26,9 +26,6 @@ gold: - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png - - url: https://fine.dev?ref=fastapibadge - title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" - img: https://fastapi.tiangolo.com/img/sponsors/fine.png - url: https://liblab.com?utm_source=fastapi title: liblab - Generate SDKs from FastAPI img: https://fastapi.tiangolo.com/img/sponsors/liblab.png diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 463c5af3b..462907e7c 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -76,12 +76,6 @@
          -
          From 847296e885ed83bc333b6cc0a3000d6242083b87 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 26 Sep 2024 17:17:48 +0000 Subject: [PATCH 292/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8a6f2d8be..885112a6a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). From f0ebae6e9ec1fdbef7720968ee9eadf5d9ad8045 Mon Sep 17 00:00:00 2001 From: Anderson Rocha Date: Fri, 4 Oct 2024 11:55:49 +0100 Subject: [PATCH 293/356] =?UTF-8?q?=20=F0=9F=8C=90=20Update=20Portuguese?= =?UTF-8?q?=20translation=20for=20`docs/pt/docs/advanced/security/http-bas?= =?UTF-8?q?ic-auth.md`=20(#12275)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md index 12b8ab01c..103d622c7 100644 --- a/docs/pt/docs/advanced/security/http-basic-auth.md +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -62,7 +62,7 @@ Utilize uma dependência para verificar se o usuário e a senha estão corretos. Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha. -O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em Inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. +O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8. @@ -106,11 +106,11 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password == ... ``` -Porém ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "ataque de temporização (timing attacks)". +Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks" (ataques de temporização). ### Ataques de Temporização -Mas o que é um "ataque de temporização"? +Mas o que é um "timing attack" (ataque de temporização)? Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha. @@ -125,7 +125,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish": Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos". -Mas então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. +Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. E a sua aplicação faz algo como: @@ -134,11 +134,11 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ... ``` -O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microsegundos a mais para retornar "Usuário ou senha incorretos". +O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos". #### O tempo para responder ajuda os invasores -Neste ponto, ao perceber que o servidor demorou alguns microsegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. +Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`. @@ -150,16 +150,16 @@ Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o us #### Corrija com o `secrets.compare_digest()` -Mas em nosso código nós estamos utilizando o `secrets.compare_digest()`. +Mas em nosso código já estamos utilizando o `secrets.compare_digest()`. Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha. -Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela esterá a salvo contra toda essa gama de ataques de segurança. +Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança. ### Retorne o erro -Depois de detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: +Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: //// tab | Python 3.9+ From 919721ce8d08c04e5dbf657481502539a92ddad0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 10:56:12 +0000 Subject: [PATCH 294/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 885112a6a..242981548 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). * ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). * 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen). From 0030f1749e4e74a4cfd58f59d85f7c4c279d239d Mon Sep 17 00:00:00 2001 From: kkotipy Date: Fri, 4 Oct 2024 19:57:17 +0900 Subject: [PATCH 295/356] =?UTF-8?q?=F0=9F=8C=90=20Fix=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/index.md`=20(#12278)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index d00a942f0..a148bc76e 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -30,7 +30,7 @@ $ uvicorn main:app --reload 코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다. -로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 비로소 경험할 수 있습니다. +로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 이점을 비로소 경험할 수 있습니다. --- From ca68c99a6eebec8d665517a88e34a514255aa36b Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 4 Oct 2024 07:58:03 -0300 Subject: [PATCH 296/356] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/tutorial/cookie-params.md`=20(#?= =?UTF-8?q?12297)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/cookie-params.md | 109 +++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 6 deletions(-) diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index caed17632..bb59dcd2c 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,21 +6,118 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + ## Declare parâmetros de `Cookie` Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e `Query`. -O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: +Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: + + +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -/// note | "Detalhes Técnicos" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | Detalhes Técnicos `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. @@ -28,9 +125,9 @@ Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fa /// -/// info | "Informação" +/// info | Informação -Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +Para declarar cookies, você precisa usar `Cookie`, pois caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. /// From ed477ee8873219398289b0ef7e2a750151410a0b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 10:58:40 +0000 Subject: [PATCH 297/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 242981548..d7482cc46 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). * ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). From 69921b463ef1669807cc2d793cc9f0193da403cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Fri, 4 Oct 2024 08:00:29 -0300 Subject: [PATCH 298/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/response-directly.md`=20(?= =?UTF-8?q?#12266)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/response-directly.md | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs/pt/docs/advanced/response-directly.md diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md new file mode 100644 index 000000000..fc571d39b --- /dev/null +++ b/docs/pt/docs/advanced/response-directly.md @@ -0,0 +1,70 @@ +# Retornando uma Resposta Diretamente + +Quando você cria uma *operação de rota* no **FastAPI** você pode retornar qualquer dado nela: um dicionário (`dict`), uma lista (`list`), um modelo do Pydantic ou do seu banco de dados, etc. + +Por padrão, o **FastAPI** irá converter automaticamente o valor do retorno para JSON utilizando o `jsonable_encoder` explicado em [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +Então, por baixo dos panos, ele incluiria esses dados compatíveis com JSON (e.g. um `dict`) dentro de uma `JSONResponse` que é utilizada para enviar uma resposta para o cliente. + +Mas você pode retornar a `JSONResponse` diretamente nas suas *operações de rota*. + +Pode ser útil para retornar cabeçalhos e cookies personalizados, por exemplo. + +## Retornando uma `Response` + +Na verdade, você pode retornar qualquer `Response` ou subclasse dela. + +/// tip | Dica + +A própria `JSONResponse` é uma subclasse de `Response`. + +/// + +E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente. + +Ele não vai fazer conversões de dados com modelos do Pydantic, não irá converter a tipagem de nenhum conteúdo, etc. + +Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc. + +## Utilizando o `jsonable_encoder` em uma `Response` + +Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso. + +Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON. + +Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: + +```Python hl_lines="6-7 21-22" +{!../../../docs_src/response_directly/tutorial001.py!} +``` + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette. + +/// + +## Retornando uma `Response` + +O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão. + +Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada. + +Vamos dizer quer retornar uma resposta XML. + +Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo: + +```Python hl_lines="1 18" +{!../../../docs_src/response_directly/tutorial002.py!} +``` + +## Notas + +Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente. + +Mas você ainda pode documentar como descrito em [Retornos Adicionais no OpenAPI +](additional-responses.md){.internal-link target=_blank}. + +Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados. From 98d190f780691fa3a8cc3abdc9805f05e6a1b751 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:01:25 +0000 Subject: [PATCH 299/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7482cc46..f66e72753 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). From b1c03ba57e50c25c6e40501bb87ce4063a91e885 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:03:27 +0000 Subject: [PATCH 300/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f66e72753..c871e1c71 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). From fa50b0c73cbf2bc298c596dda8f79e4789608341 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 4 Oct 2024 08:03:46 -0300 Subject: [PATCH 301/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/conditional-openapi.md`=20(?= =?UTF-8?q?#12221)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/conditional-openapi.md | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/pt/docs/how-to/conditional-openapi.md diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..cfa652fa5 --- /dev/null +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -0,0 +1,58 @@ +# OpenAPI condicional + +Se necessário, você pode usar configurações e variáveis ​​de ambiente para configurar o OpenAPI condicionalmente, dependendo do ambiente, e até mesmo desativá-lo completamente. + +## Sobre segurança, APIs e documentos + +Ocultar suas interfaces de usuário de documentação na produção *não deveria* ser a maneira de proteger sua API. + +Isso não adiciona nenhuma segurança extra à sua API; as *operações de rotas* ainda estarão disponíveis onde estão. + +Se houver uma falha de segurança no seu código, ela ainda existirá. + +Ocultar a documentação apenas torna mais difícil entender como interagir com sua API e pode dificultar sua depuração na produção. Pode ser considerado simplesmente uma forma de Segurança através da obscuridade. + +Se você quiser proteger sua API, há várias coisas melhores que você pode fazer, por exemplo: + +* Certifique-se de ter modelos Pydantic bem definidos para seus corpos de solicitação e respostas. +* Configure quaisquer permissões e funções necessárias usando dependências. +* Nunca armazene senhas em texto simples, apenas hashes de senha. +* Implemente e use ferramentas criptográficas bem conhecidas, como tokens JWT e Passlib, etc. +* Adicione controles de permissão mais granulares com escopos OAuth2 quando necessário. +* ...etc. + +No entanto, você pode ter um caso de uso muito específico em que realmente precisa desabilitar a documentação da API para algum ambiente (por exemplo, para produção) ou dependendo de configurações de variáveis ​​de ambiente. + +## OpenAPI condicional com configurações e variáveis ​​de ambiente + +Você pode usar facilmente as mesmas configurações do Pydantic para configurar sua OpenAPI gerada e as interfaces de usuário de documentos. + +Por exemplo: + +```Python hl_lines="6 11" +{!../../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. + +E então o usamos ao criar o aplicativo `FastAPI`. + +Então você pode desabilitar o OpenAPI (incluindo os documentos da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como uma string vazia, como: + +
          + +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
          + +Então, se você acessar as URLs em `/openapi.json`, `/docs` ou `/redoc`, você receberá apenas um erro `404 Não Encontrado` como: + +```JSON +{ + "detail": "Not Found" +} +``` From 17e234452abc3dce895e2e2e93c48f856dd43da3 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 4 Oct 2024 08:04:50 -0300 Subject: [PATCH 302/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/deployment/concepts.md`=20(#12219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/concepts.md | 321 ++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 docs/pt/docs/deployment/concepts.md diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md new file mode 100644 index 000000000..20513c366 --- /dev/null +++ b/docs/pt/docs/deployment/concepts.md @@ -0,0 +1,321 @@ +# Conceitos de Implantações + +Ao implantar um aplicativo **FastAPI**, ou na verdade, qualquer tipo de API da web, há vários conceitos com os quais você provavelmente se importa e, usando-os, você pode encontrar a maneira **mais apropriada** de **implantar seu aplicativo**. + +Alguns dos conceitos importantes são: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Veremos como eles afetariam as **implantações**. + +No final, o principal objetivo é ser capaz de **atender seus clientes de API** de uma forma **segura**, **evitar interrupções** e usar os **recursos de computação** (por exemplo, servidores remotos/máquinas virtuais) da forma mais eficiente possível. 🚀 + +Vou lhe contar um pouco mais sobre esses **conceitos** aqui, e espero que isso lhe dê a **intuição** necessária para decidir como implantar sua API em ambientes muito diferentes, possivelmente até mesmo em **futuros** ambientes que ainda não existem. + +Ao considerar esses conceitos, você será capaz de **avaliar e projetar** a melhor maneira de implantar **suas próprias APIs**. + +Nos próximos capítulos, darei a você mais **receitas concretas** para implantar aplicativos FastAPI. + +Mas por enquanto, vamos verificar essas importantes **ideias conceituais**. Esses conceitos também se aplicam a qualquer outro tipo de API da web. 💡 + +## Segurança - HTTPS + +No [capítulo anterior sobre HTTPS](https.md){.internal-link target=_blank} aprendemos como o HTTPS fornece criptografia para sua API. + +Também vimos que o HTTPS normalmente é fornecido por um componente **externo** ao seu servidor de aplicativos, um **Proxy de terminação TLS**. + +E tem que haver algo responsável por **renovar os certificados HTTPS**, pode ser o mesmo componente ou pode ser algo diferente. + +### Ferramentas de exemplo para HTTPS + +Algumas das ferramentas que você pode usar como um proxy de terminação TLS são: + +* Traefik + * Lida automaticamente com renovações de certificados ✨ +* Caddy + * Lida automaticamente com renovações de certificados ✨ +* Nginx + * Com um componente externo como o Certbot para renovações de certificados +* HAProxy + * Com um componente externo como o Certbot para renovações de certificados +* Kubernetes com um controlador Ingress como o Nginx + * Com um componente externo como cert-manager para renovações de certificados +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços (leia abaixo 👇) + +Outra opção é que você poderia usar um **serviço de nuvem** que faz mais do trabalho, incluindo a configuração de HTTPS. Ele pode ter algumas restrições ou cobrar mais, etc. Mas, nesse caso, você não teria que configurar um Proxy de terminação TLS sozinho. + +Mostrarei alguns exemplos concretos nos próximos capítulos. + +--- + +Os próximos conceitos a serem considerados são todos sobre o programa que executa sua API real (por exemplo, Uvicorn). + +## Programa e Processo + +Falaremos muito sobre o "**processo**" em execução, então é útil ter clareza sobre o que ele significa e qual é a diferença com a palavra "**programa**". + +### O que é um Programa + +A palavra **programa** é comumente usada para descrever muitas coisas: + +* O **código** que você escreve, os **arquivos Python**. +* O **arquivo** que pode ser **executado** pelo sistema operacional, por exemplo: `python`, `python.exe` ou `uvicorn`. +* Um programa específico enquanto está **em execução** no sistema operacional, usando a CPU e armazenando coisas na memória. Isso também é chamado de **processo**. + +### O que é um Processo + +A palavra **processo** normalmente é usada de forma mais específica, referindo-se apenas ao que está sendo executado no sistema operacional (como no último ponto acima): + +* Um programa específico enquanto está **em execução** no sistema operacional. + * Isso não se refere ao arquivo, nem ao código, refere-se **especificamente** à coisa que está sendo **executada** e gerenciada pelo sistema operacional. +* Qualquer programa, qualquer código, **só pode fazer coisas** quando está sendo **executado**. Então, quando há um **processo em execução**. +* O processo pode ser **terminado** (ou "morto") por você, ou pelo sistema operacional. Nesse ponto, ele para de rodar/ser executado, e ele **não pode mais fazer coisas**. +* Cada aplicativo que você tem em execução no seu computador tem algum processo por trás dele, cada programa em execução, cada janela, etc. E normalmente há muitos processos em execução **ao mesmo tempo** enquanto um computador está ligado. +* Pode haver **vários processos** do **mesmo programa** em execução ao mesmo tempo. + +Se você verificar o "gerenciador de tarefas" ou o "monitor do sistema" (ou ferramentas semelhantes) no seu sistema operacional, poderá ver muitos desses processos em execução. + +E, por exemplo, você provavelmente verá que há vários processos executando o mesmo programa de navegador (Firefox, Chrome, Edge, etc.). Eles normalmente executam um processo por aba, além de alguns outros processos extras. + + + +--- + +Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações. + +## Executando na inicialização + +Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**. + +### Em um servidor remoto + +Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente. + +E funcionará e será útil **durante o desenvolvimento**. + +Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá. + +E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱 + +### Executar automaticamente na inicialização + +Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI). + +### Programa separado + +Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados. + +### Ferramentas de exemplo para executar na inicialização + +Alguns exemplos de ferramentas que podem fazer esse trabalho são: + +* Docker +* Kubernetes +* Docker Compose +* Docker em Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +Darei exemplos mais concretos nos próximos capítulos. + +## Reinicializações + +Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas. + +### Nós cometemos erros + +Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛 + +E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅). + +### Pequenos erros são tratados automaticamente + +Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡 + +O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente. + +### Erros maiores - Travamentos + +No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥 + +E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de caminho* que não estão quebradas. + +### Reiniciar após falha + +Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes... + +/// tip | "Dica" + +...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação. + +Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo. + +/// + +Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito. + +### Ferramentas de exemplo para reiniciar automaticamente + +Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas. + +Por exemplo, isso poderia ser resolvido por: + +* Docker +* Kubernetes +* Docker Compose +* Docker no Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +## Replicação - Processos e Memória + +Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente. + +Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo. + +### Processos Múltiplos - Trabalhadores + +Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles. + +Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**. + +### Processos do Trabalhador e Portas + +Lembra da documentação [Sobre HTTPS](https.md){.internal-link target=_blank} que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor? + +Isso ainda é verdade. + +Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma. + +### Memória por Processo + +Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor. + +E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis ​​e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória. + +### Memória do servidor + +Por exemplo, se seu código carrega um modelo de Machine Learning com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**. + +E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨 + +### Processos Múltiplos - Um Exemplo + +Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**. + +Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho. + +Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis ​​na RAM. + + + +E, claro, a mesma máquina provavelmente teria **outros processos** em execução, além do seu aplicativo. + +Um detalhe interessante é que a porcentagem da **CPU usada** por cada processo pode **variar** muito ao longo do tempo, mas a **memória (RAM)** normalmente fica mais ou menos **estável**. + +Se você tiver uma API que faz uma quantidade comparável de cálculos todas as vezes e tiver muitos clientes, então a **utilização da CPU** provavelmente *também será estável* (em vez de ficar constantemente subindo e descendo rapidamente). + +### Exemplos de ferramentas e estratégias de replicação + +Pode haver várias abordagens para conseguir isso, e falarei mais sobre estratégias específicas nos próximos capítulos, por exemplo, ao falar sobre Docker e contêineres. + +A principal restrição a ser considerada é que tem que haver um **único** componente manipulando a **porta** no **IP público**. E então tem que ter uma maneira de **transmitir** a comunicação para os **processos/trabalhadores** replicados. + +Aqui estão algumas combinações e estratégias possíveis: + +* **Uvicorn** com `--workers` + * Um **gerenciador de processos** Uvicorn escutaria no **IP** e na **porta** e iniciaria **vários processos de trabalho Uvicorn**. +* **Kubernetes** e outros **sistemas de contêineres** distribuídos + * Algo na camada **Kubernetes** escutaria no **IP** e na **porta**. A replicação seria por ter **vários contêineres**, cada um com **um processo Uvicorn** em execução. +* **Serviços de nuvem** que cuidam disso para você + * O serviço de nuvem provavelmente **cuidará da replicação para você**. Ele possivelmente deixaria você definir **um processo para executar**, ou uma **imagem de contêiner** para usar, em qualquer caso, provavelmente seria **um único processo Uvicorn**, e o serviço de nuvem seria responsável por replicá-lo. + +/// tip | "Dica" + +Não se preocupe se alguns desses itens sobre **contêineres**, Docker ou Kubernetes ainda não fizerem muito sentido. + +Falarei mais sobre imagens de contêiner, Docker, Kubernetes, etc. em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Etapas anteriores antes de começar + +Há muitos casos em que você deseja executar algumas etapas **antes de iniciar** sua aplicação. + +Por exemplo, você pode querer executar **migrações de banco de dados**. + +Mas na maioria dos casos, você precisará executar essas etapas apenas **uma vez**. + +Portanto, você vai querer ter um **processo único** para executar essas **etapas anteriores** antes de iniciar o aplicativo. + +E você terá que se certificar de que é um único processo executando essas etapas anteriores *mesmo* se depois, você iniciar **vários processos** (vários trabalhadores) para o próprio aplicativo. Se essas etapas fossem executadas por **vários processos**, eles **duplicariam** o trabalho executando-o em **paralelo**, e se as etapas fossem algo delicado como uma migração de banco de dados, elas poderiam causar conflitos entre si. + +Claro, há alguns casos em que não há problema em executar as etapas anteriores várias vezes; nesse caso, é muito mais fácil de lidar. + +/// tip | "Dica" + +Além disso, tenha em mente que, dependendo da sua configuração, em alguns casos você **pode nem precisar de nenhuma etapa anterior** antes de iniciar sua aplicação. + +Nesse caso, você não precisaria se preocupar com nada disso. 🤷 + +/// + +### Exemplos de estratégias de etapas anteriores + +Isso **dependerá muito** da maneira como você **implanta seu sistema** e provavelmente estará conectado à maneira como você inicia programas, lida com reinicializações, etc. + +Aqui estão algumas ideias possíveis: + +* Um "Init Container" no Kubernetes que roda antes do seu app container +* Um script bash que roda os passos anteriores e então inicia seu aplicativo + * Você ainda precisaria de uma maneira de iniciar/reiniciar *aquele* script bash, detectar erros, etc. + +/// tip | "Dica" + +Darei exemplos mais concretos de como fazer isso com contêineres em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Utilização de recursos + +Seu(s) servidor(es) é(são) um **recurso** que você pode consumir ou **utilizar**, com seus programas, o tempo de computação nas CPUs e a memória RAM disponível. + +Quanto dos recursos do sistema você quer consumir/utilizar? Pode ser fácil pensar "não muito", mas, na realidade, você provavelmente vai querer consumir **o máximo possível sem travar**. + +Se você está pagando por 3 servidores, mas está usando apenas um pouco de RAM e CPU, você provavelmente está **desperdiçando dinheiro** 💸, e provavelmente **desperdiçando energia elétrica do servidor** 🌎, etc. + +Nesse caso, seria melhor ter apenas 2 servidores e usar uma porcentagem maior de seus recursos (CPU, memória, disco, largura de banda de rede, etc). + +Por outro lado, se você tem 2 servidores e está usando **100% da CPU e RAM deles**, em algum momento um processo pedirá mais memória, e o servidor terá que usar o disco como "memória" (o que pode ser milhares de vezes mais lento), ou até mesmo **travar**. Ou um processo pode precisar fazer alguma computação e teria que esperar até que a CPU esteja livre novamente. + +Nesse caso, seria melhor obter **um servidor extra** e executar alguns processos nele para que todos tenham **RAM e tempo de CPU suficientes**. + +Também há a chance de que, por algum motivo, você tenha um **pico** de uso da sua API. Talvez ela tenha se tornado viral, ou talvez alguns outros serviços ou bots comecem a usá-la. E você pode querer ter recursos extras para estar seguro nesses casos. + +Você poderia colocar um **número arbitrário** para atingir, por exemplo, algo **entre 50% a 90%** da utilização de recursos. O ponto é que essas são provavelmente as principais coisas que você vai querer medir e usar para ajustar suas implantações. + +Você pode usar ferramentas simples como `htop` para ver a CPU e a RAM usadas no seu servidor ou a quantidade usada por cada processo. Ou você pode usar ferramentas de monitoramento mais complexas, que podem ser distribuídas entre servidores, etc. + +## Recapitular + +Você leu aqui alguns dos principais conceitos que provavelmente precisa ter em mente ao decidir como implantar seu aplicativo: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Entender essas ideias e como aplicá-las deve lhe dar a intuição necessária para tomar qualquer decisão ao configurar e ajustar suas implantações. 🤓 + +Nas próximas seções, darei exemplos mais concretos de possíveis estratégias que você pode seguir. 🚀 From 304f514ed95107a32e7b1f263003720b9475c580 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:08:00 +0000 Subject: [PATCH 303/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c871e1c71..ca8dcedb0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). From 5820d4261e2784cfabbe5358015142d71039555a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:10:09 +0000 Subject: [PATCH 304/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ca8dcedb0..7188a698f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). From 0e7806e3f97ad16a526e77488a72be62359890e1 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 4 Oct 2024 08:11:41 -0300 Subject: [PATCH 305/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/security/oauth2-scopes.md?= =?UTF-8?q?`=20(#12263)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/oauth2-scopes.md | 786 ++++++++++++++++++ 1 file changed, 786 insertions(+) create mode 100644 docs/pt/docs/advanced/security/oauth2-scopes.md diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..4ad7c807e --- /dev/null +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,786 @@ +# Escopos OAuth2 + +Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente. + +Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API). + +OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações. + +Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitter, aquela aplicação está utilizando o OAuth2 com escopos. + +Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. + +/// warning | "Aviso" + +Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. + +Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor. + +Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API. + +No entando, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código. + +Em muitos casos, OAuth2 com escopos pode ser um exagero. + +Mas se você sabe que precisa, ou está curioso, continue lendo. + +/// + +## Escopos OAuth2 e OpenAPI + +A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços. + +O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços. + +Estes escopos representam "permissões". + +No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança". + +Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos. + +Cada "escopo" é apenas uma string (sem espaços). + +Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo: + +* `users:read` or `users:write` são exemplos comuns. +* `instagram_basic` é utilizado pelo Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` é utilizado pelo Google. + +/// info | Informação + +No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária. + +Não importa se ela contém outros caracteres como `:` ou se ela é uma URL. + +Estes detalhes são específicos da implementação. + +Para o OAuth2, eles são apenas strings. + +/// + +## Visão global + +Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: + +//// tab | Python 3.10+ + +```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +Agora vamos revisar essas mudanças passo a passo. + +## Esquema de segurança OAuth2 + +A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`. + +O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: + +//// tab | Python 3.10+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="64-67" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. + +E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`. + +Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc: + + + +## Token JWT com escopos + +Agora, modifique o *caminho de rota* para retornar os escopos solicitados. + +Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição. + +E nós retornamos os escopos como parte do token JWT. + +/// danger | Cuidado + +Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token. + +Porém em sua aplicação, por segurança, você deve garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Declare escopos em *operações de rota* e dependências + +Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`. + +Para isso, nós importamos e utilizamos `Security` de `fastapi`. + +Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetros `scopes` com uma lista de escopos (strings). + +Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`). + +Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais). + +E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo. + +Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). + +/// note | "Nota" + +Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. + +Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 141 172" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +/// info | Informações Técnicas + +`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois. + +Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI. + +Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais. + +/// + +## Utilize `SecurityScopes` + +Agora atualize a dependência `get_current_user`. + +Este é o usado pelas dependências acima. + +Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`. + +Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança. + +Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`. + +A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). + +//// tab | Python 3.10+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 107" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Utilize os `scopes` + +O parâmetro `security_scopes` será do tipo `SecurityScopes`. + +Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante. + +O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso). + +Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares. + +Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). + +//// tab | Python 3.10+ + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="107 109-117" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique o `username` e o formato dos dados + +Nós verificamos que nós obtemos um `username`, e extraímos os escopos. + +E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente. + +Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`. + +Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`. + +No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança. + +Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. + +//// tab | Python 3.10+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="48 118-129" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique os `scopes` + +Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`. + +Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. + +//// tab | Python 3.10+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="130-136" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Árvore de dependência e escopos + +Vamos rever novamente essa árvore de dependência e os escopos. + +Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`. + +A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`. + +Aqui está como a hierarquia de dependências e escopos parecem: + +* A *operação de rota* `read_own_items` possui: + * Escopos necessários `["items"]` com a dependência: + * `get_current_active_user`: + * A função de dependência `get_current_active_user` possui: + * Escopos necessários `["me"]` com a dependência: + * `get_current_user`: + * A função de dependência `get_current_user` possui: + * Nenhum escopo necessário. + * Uma dependência utilizando `oauth2_scheme`. + * Um parâmetro `security_scopes` do tipo `SecurityScopes`: + * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então: + * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`. + * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`. + * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também. + +/// tip | Dica + +A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*. + +Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica. + +/// + +## Mais detalhes sobre `SecurityScopes` + +Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz". + +Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**. + +Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*. + +Todos eles serão validados independentemente para cada *operação de rota*. + +## Verifique + +Se você abrir os documentos da API, você pode antenticar e especificar quais escopos você quer autorizar. + + + +Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`. + +E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`. + +Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação. + +## Sobre integrações de terceiros + +Neste exemplos nós estamos utilizando o fluxo de senha do OAuth2. + +Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*". + +Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso. + +Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos. + +O mais comum é o fluxo implícito. + +O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. + +/// note | "Nota" + +É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. + +Mas no final, eles estão implementando o mesmo padrão OAuth2. + +/// + +O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`. + +## `Security` em docoradores de `dependências` + +Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro de `dependencias` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), você também pode utilizar `Security` com escopos lá. From e2217e24b9895adf5d6f8ef25c491fca4f1bdafb Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:14:33 +0000 Subject: [PATCH 306/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7188a698f..e2b5808a4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From a681aeba6d7112b9351a11ca5a1756de4e27d370 Mon Sep 17 00:00:00 2001 From: AnandaCampelo <103457620+AnandaCampelo@users.noreply.github.com> Date: Fri, 4 Oct 2024 08:15:21 -0300 Subject: [PATCH 307/356] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/graphql.md`=20(#12215)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/graphql.md | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 docs/pt/docs/how-to/graphql.md diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md new file mode 100644 index 000000000..0b711aa5e --- /dev/null +++ b/docs/pt/docs/how-to/graphql.md @@ -0,0 +1,62 @@ +# GraphQL + +Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI. + +Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação. + +/// tip | "Dica" + +**GraphQL** resolve alguns casos de uso muito específicos. + +Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns. + +Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓 + +/// + +## Bibliotecas GraphQL + +Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**: + +* Strawberry 🍓 + * Com docs para FastAPI +* Ariadne + * Com docs para FastAPI +* Tartiflette + * Com Tartiflette ASGI para fornecer integração ASGI +* Graphene + * Com starlette-graphene3 + +## GraphQL com Strawberry + +Se você precisar ou quiser trabalhar com **GraphQL**, **Strawberry** é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **type annotations**. + +Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**. + +Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Você pode aprender mais sobre Strawberry na documentação do Strawberry. + +E também na documentação sobre Strawberry com FastAPI. + +## Antigo `GraphQLApp` do Starlette + +Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com Graphene. + +Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. + +/// tip | "Dica" + +Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. + +/// + +## Saiba Mais + +Você pode aprender mais sobre **GraphQL** na documentação oficial do GraphQL. + +Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links. From c93810e0975a1f488f9d9d0a5b7a845b4d447a96 Mon Sep 17 00:00:00 2001 From: Kayque Govetri <59173212+kayqueGovetri@users.noreply.github.com> Date: Fri, 4 Oct 2024 08:16:34 -0300 Subject: [PATCH 308/356] =?UTF-8?q?=F0=9F=93=9D=20Adding=20links=20for=20P?= =?UTF-8?q?laywright=20and=20Vite=20in=20`docs/project-generation.md`=20(#?= =?UTF-8?q?12274)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/project-generation.md | 4 ++-- docs/es/docs/project-generation.md | 4 ++-- docs/ko/docs/project-generation.md | 4 ++-- docs/zh/docs/project-generation.md | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index 61459ba53..665bc54f9 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -13,10 +13,10 @@ GitHub Repository: Date: Fri, 4 Oct 2024 11:20:35 +0000 Subject: [PATCH 309/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e2b5808a4..d205d96ac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/graphql.md`. PR [#12215](https://github.com/fastapi/fastapi/pull/12215) by [@AnandaCampelo](https://github.com/AnandaCampelo). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). From 3d2483327234182791cd6855b180aa61936eaf05 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:20:57 +0000 Subject: [PATCH 310/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d205d96ac..bbc8ac14e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri). * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). ### Translations From a096615f79cb428b68b4478fe5d53e2cf43f6ca2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:21:41 +0200 Subject: [PATCH 311/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12331)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.7 → v0.6.8](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.7...v0.6.8) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1502f0abd..48a7d495c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.7 + rev: v0.6.8 hooks: - id: ruff args: From f2fb0251cc22b1a7c7a2a65b3f6ee68750353af5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:26:21 +0000 Subject: [PATCH 312/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bbc8ac14e..82012b1af 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). From 3f3a3dd6640f0639f27202cf049fb9b24b6c53a6 Mon Sep 17 00:00:00 2001 From: Pavlo Pohorieltsev <49622129+makisukurisu@users.noreply.github.com> Date: Fri, 4 Oct 2024 14:34:57 +0300 Subject: [PATCH 313/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20link=20to=20Swa?= =?UTF-8?q?gger=20UI=20configuration=20docs=20(#12264)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/en/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/pt/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/zh/docs/how-to/configure-swagger-ui.md | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index c18091efd..7d62a14d3 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Swagger-Oberfläche konfigurieren -Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. +Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. @@ -58,7 +58,7 @@ Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellu ## Andere Parameter der Swagger-Oberfläche -Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. ## JavaScript-basierte Einstellungen diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index 108afb929..040c3926b 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configure Swagger UI -You can configure some extra Swagger UI parameters. +You can configure some extra Swagger UI parameters. To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. @@ -58,7 +58,7 @@ For example, to disable `deepLinking` you could pass these settings to `swagger_ ## Other Swagger UI Parameters -To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. +To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. ## JavaScript-only settings diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index b40dad695..ceb8c634e 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configurar Swagger UI -Você pode configurar alguns parâmetros extras da UI do Swagger. +Você pode configurar alguns parâmetros extras da UI do Swagger. Para configurá-los, passe o argumento `swagger_ui_parameters` ao criar o objeto de aplicativo `FastAPI()` ou para a função `get_swagger_ui_html()`. @@ -58,7 +58,7 @@ Por exemplo, para desabilitar `deepLinking` você pode passar essas configuraç ## Outros parâmetros da UI do Swagger -Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. +Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. ## Configurações somente JavaScript diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index c0d09f943..17f89b22f 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # 配置 Swagger UI -你可以配置一些额外的 Swagger UI 参数. +你可以配置一些额外的 Swagger UI 参数. 如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 @@ -58,7 +58,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 ## 其他 Swagger UI 参数 -查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 +查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 ## JavaScript-only 配置 From d12db0b26c11d338bba3f0099a6236b5931224dd Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:36:26 +0000 Subject: [PATCH 314/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 82012b1af..744377757 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu). * 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri). * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). From 8953d9a3234968d3673eddbeb947e42f34d3536a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:37:26 +0200 Subject: [PATCH 315/356] =?UTF-8?q?=E2=AC=86=20Bump=20griffe-typingdoc=20f?= =?UTF-8?q?rom=200.2.6=20to=200.2.7=20(#12370)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc) from 0.2.6 to 0.2.7. - [Release notes](https://github.com/mkdocstrings/griffe-typingdoc/releases) - [Changelog](https://github.com/mkdocstrings/griffe-typingdoc/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/griffe-typingdoc/compare/0.2.6...0.2.7) --- updated-dependencies: - dependency-name: griffe-typingdoc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 332fd1857..70dca9f2f 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -12,7 +12,7 @@ pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 -griffe-typingdoc==0.2.6 +griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 From deec2e591e6fb506c4249340b1b96c0b2afd4b07 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:39:01 +0000 Subject: [PATCH 316/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 744377757..8fbb26bb0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 757eaacd5950ab355807ebf4f9e80dd17bd56b20 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:56:35 +0200 Subject: [PATCH 317/356] =?UTF-8?q?=E2=AC=86=20Bump=20mkdocstrings[python]?= =?UTF-8?q?=20from=200.25.1=20to=200.26.1=20(#12371)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [mkdocstrings[python]](https://github.com/mkdocstrings/mkdocstrings) from 0.25.1 to 0.26.1. - [Release notes](https://github.com/mkdocstrings/mkdocstrings/releases) - [Changelog](https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/mkdocstrings/compare/0.25.1...0.26.1) --- updated-dependencies: - dependency-name: mkdocstrings[python] dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 70dca9f2f..16b2998b9 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -11,7 +11,7 @@ jieba==0.42.1 pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 -mkdocstrings[python]==0.25.1 +mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 From 82b95dcef8d032628217599ea8700260d1ecc670 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:56:57 +0000 Subject: [PATCH 318/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8fbb26bb0..77daba91c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). From caa298aefea0ddbd373368b87a740b3bd08e4e42 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:57:23 +0200 Subject: [PATCH 319/356] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.10.1=20to=201.10.3=20(#12386)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.10.1 to 1.10.3. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.10.1...v1.10.3) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5004b94dd..c8ea4e18c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.1 + uses: pypa/gh-action-pypi-publish@v1.10.3 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From ea1265b78beb2a7a1991a6dd4e8f19852ffa3196 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:58:03 +0000 Subject: [PATCH 320/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 77daba91c..6660ea894 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 9d6ec4aa77f613a99c8f05d8f8a0d2088a2a2d00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 5 Oct 2024 14:49:04 +0200 Subject: [PATCH 321/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20Cloudflare=20Gi?= =?UTF-8?q?tHub=20Action=20(#12387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index d2953f284..c7827f132 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -55,14 +55,14 @@ jobs: # hashFiles returns an empty string if there are no files if: hashFiles('./site/*') id: deploy - uses: cloudflare/pages-action@v1 + env: + PROJECT_NAME: fastapitiangolo + BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - projectName: fastapitiangolo - directory: './site' - gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }} - name: Comment Deploy run: python ./scripts/deploy_docs_status.py env: From ad8b3ba3ec5e41f7ebf85791870cab40f0429517 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 5 Oct 2024 12:49:28 +0000 Subject: [PATCH 322/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6660ea894..ddbaee46b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). From 1705a8c37f047df61564e47dd8c050d6213def81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 6 Oct 2024 22:14:05 +0200 Subject: [PATCH 323/356] =?UTF-8?q?=F0=9F=91=B7=20Update=20deploy-docs-not?= =?UTF-8?q?ify=20URL=20(#12392)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index c7827f132..22dc89dff 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -67,7 +67,7 @@ jobs: run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DEPLOY_URL: ${{ steps.deploy.outputs.url }} + DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.run_id }} IS_DONE: "true" From c67b41546cd322cb61e25cc275e995902519ca68 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 6 Oct 2024 20:14:33 +0000 Subject: [PATCH 324/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ddbaee46b..2995aa8df 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). From 0f7d67e85c9b99c82821c9cfde51721dd98698a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 6 Oct 2024 22:36:54 +0200 Subject: [PATCH 325/356] =?UTF-8?q?=F0=9F=94=A7=20Remove=20`base=5Fpath`?= =?UTF-8?q?=20for=20`mdx=5Finclude`=20Markdown=20extension=20in=20MkDocs?= =?UTF-8?q?=20(#12391)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/python-types.md | 56 +++---- docs/de/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../de/docs/advanced/advanced-dependencies.md | 24 +-- docs/de/docs/advanced/async-tests.md | 8 +- docs/de/docs/advanced/behind-a-proxy.md | 10 +- docs/de/docs/advanced/custom-response.md | 32 ++-- docs/de/docs/advanced/dataclasses.md | 6 +- docs/de/docs/advanced/events.md | 12 +- docs/de/docs/advanced/generate-clients.md | 16 +- docs/de/docs/advanced/middleware.md | 6 +- docs/de/docs/advanced/openapi-callbacks.md | 8 +- docs/de/docs/advanced/openapi-webhooks.md | 2 +- .../path-operation-advanced-configuration.md | 20 +-- .../advanced/response-change-status-code.md | 2 +- docs/de/docs/advanced/response-cookies.md | 4 +- docs/de/docs/advanced/response-directly.md | 4 +- docs/de/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/de/docs/advanced/settings.md | 36 ++--- docs/de/docs/advanced/sub-applications.md | 6 +- docs/de/docs/advanced/templates.md | 8 +- docs/de/docs/advanced/testing-dependencies.md | 10 +- docs/de/docs/advanced/testing-events.md | 2 +- docs/de/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/de/docs/advanced/websockets.md | 20 +-- docs/de/docs/advanced/wsgi.md | 2 +- docs/de/docs/how-to/conditional-openapi.md | 2 +- docs/de/docs/how-to/configure-swagger-ui.md | 8 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 14 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/de/docs/how-to/extending-openapi.md | 10 +- docs/de/docs/how-to/graphql.md | 2 +- .../docs/how-to/separate-openapi-schemas.md | 36 ++--- docs/de/docs/python-types.md | 56 +++---- docs/de/docs/tutorial/background-tasks.md | 16 +- docs/de/docs/tutorial/bigger-applications.md | 30 ++-- docs/de/docs/tutorial/body-fields.md | 20 +-- docs/de/docs/tutorial/body-multiple-params.md | 44 +++--- docs/de/docs/tutorial/body-nested-models.md | 56 +++---- docs/de/docs/tutorial/body-updates.md | 24 +-- docs/de/docs/tutorial/body.md | 24 +-- docs/de/docs/tutorial/cookie-params.md | 20 +-- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 28 ++-- .../dependencies/global-dependencies.md | 6 +- docs/de/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/de/docs/tutorial/encoder.md | 4 +- docs/de/docs/tutorial/extra-data-types.md | 20 +-- docs/de/docs/tutorial/extra-models.md | 20 +-- docs/de/docs/tutorial/first-steps.md | 16 +- docs/de/docs/tutorial/handling-errors.md | 16 +- docs/de/docs/tutorial/header-params.md | 42 ++--- docs/de/docs/tutorial/metadata.md | 12 +- docs/de/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/de/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 142 ++++++++--------- docs/de/docs/tutorial/query-params.md | 20 +-- docs/de/docs/tutorial/request-files.md | 50 +++--- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/de/docs/tutorial/request-forms.md | 12 +- docs/de/docs/tutorial/response-model.md | 68 ++++---- docs/de/docs/tutorial/response-status-code.md | 6 +- docs/de/docs/tutorial/schema-extra-example.md | 42 ++--- docs/de/docs/tutorial/security/first-steps.md | 18 +-- .../tutorial/security/get-current-user.md | 56 +++---- docs/de/docs/tutorial/security/oauth2-jwt.md | 40 ++--- .../docs/tutorial/security/simple-oauth2.md | 50 +++--- docs/de/docs/tutorial/static-files.md | 2 +- docs/de/docs/tutorial/testing.md | 18 +-- docs/em/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../em/docs/advanced/advanced-dependencies.md | 8 +- docs/em/docs/advanced/async-tests.md | 8 +- docs/em/docs/advanced/behind-a-proxy.md | 8 +- docs/em/docs/advanced/custom-response.md | 32 ++-- docs/em/docs/advanced/dataclasses.md | 6 +- docs/em/docs/advanced/events.md | 12 +- docs/em/docs/advanced/generate-clients.md | 14 +- docs/em/docs/advanced/middleware.md | 6 +- docs/em/docs/advanced/openapi-callbacks.md | 8 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 2 +- docs/em/docs/advanced/response-cookies.md | 4 +- docs/em/docs/advanced/response-directly.md | 4 +- docs/em/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 6 +- .../docs/advanced/security/oauth2-scopes.md | 16 +- docs/em/docs/advanced/settings.md | 20 +-- docs/em/docs/advanced/sub-applications.md | 6 +- docs/em/docs/advanced/templates.md | 8 +- docs/em/docs/advanced/testing-database.md | 8 +- docs/em/docs/advanced/testing-dependencies.md | 2 +- docs/em/docs/advanced/testing-events.md | 2 +- docs/em/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/em/docs/advanced/websockets.md | 10 +- docs/em/docs/advanced/wsgi.md | 2 +- docs/em/docs/how-to/conditional-openapi.md | 2 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/em/docs/how-to/extending-openapi.md | 10 +- docs/em/docs/how-to/graphql.md | 2 +- docs/em/docs/how-to/sql-databases-peewee.md | 34 ++-- docs/em/docs/python-types.md | 52 +++---- docs/em/docs/tutorial/background-tasks.md | 10 +- docs/em/docs/tutorial/bigger-applications.md | 26 ++-- docs/em/docs/tutorial/body-fields.md | 8 +- docs/em/docs/tutorial/body-multiple-params.md | 20 +-- docs/em/docs/tutorial/body-nested-models.md | 56 +++---- docs/em/docs/tutorial/body-updates.md | 24 +-- docs/em/docs/tutorial/body.md | 24 +-- docs/em/docs/tutorial/cookie-params.md | 8 +- docs/em/docs/tutorial/cors.md | 2 +- docs/em/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 14 +- .../dependencies/global-dependencies.md | 2 +- docs/em/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/em/docs/tutorial/encoder.md | 4 +- docs/em/docs/tutorial/extra-data-types.md | 8 +- docs/em/docs/tutorial/extra-models.md | 20 +-- docs/em/docs/tutorial/first-steps.md | 16 +- docs/em/docs/tutorial/handling-errors.md | 16 +- docs/em/docs/tutorial/header-params.md | 18 +-- docs/em/docs/tutorial/metadata.md | 10 +- docs/em/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 18 +-- docs/em/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 64 ++++---- docs/em/docs/tutorial/query-params.md | 20 +-- docs/em/docs/tutorial/request-files.md | 20 +-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/em/docs/tutorial/request-forms.md | 4 +- docs/em/docs/tutorial/response-model.md | 68 ++++---- docs/em/docs/tutorial/response-status-code.md | 6 +- docs/em/docs/tutorial/schema-extra-example.md | 16 +- docs/em/docs/tutorial/security/first-steps.md | 6 +- .../tutorial/security/get-current-user.md | 22 +-- docs/em/docs/tutorial/security/oauth2-jwt.md | 16 +- .../docs/tutorial/security/simple-oauth2.md | 20 +-- docs/em/docs/tutorial/sql-databases.md | 74 ++++----- docs/em/docs/tutorial/static-files.md | 2 +- docs/em/docs/tutorial/testing.md | 12 +- docs/en/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../en/docs/advanced/advanced-dependencies.md | 24 +-- docs/en/docs/advanced/async-tests.md | 8 +- docs/en/docs/advanced/behind-a-proxy.md | 10 +- docs/en/docs/advanced/custom-response.md | 32 ++-- docs/en/docs/advanced/dataclasses.md | 6 +- docs/en/docs/advanced/events.md | 12 +- docs/en/docs/advanced/generate-clients.md | 16 +- docs/en/docs/advanced/middleware.md | 6 +- docs/en/docs/advanced/openapi-callbacks.md | 8 +- docs/en/docs/advanced/openapi-webhooks.md | 2 +- .../path-operation-advanced-configuration.md | 20 +-- .../advanced/response-change-status-code.md | 2 +- docs/en/docs/advanced/response-cookies.md | 4 +- docs/en/docs/advanced/response-directly.md | 4 +- docs/en/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/en/docs/advanced/settings.md | 36 ++--- docs/en/docs/advanced/sub-applications.md | 6 +- docs/en/docs/advanced/templates.md | 8 +- docs/en/docs/advanced/testing-database.md | 8 +- docs/en/docs/advanced/testing-dependencies.md | 10 +- docs/en/docs/advanced/testing-events.md | 2 +- docs/en/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/en/docs/advanced/websockets.md | 20 +-- docs/en/docs/advanced/wsgi.md | 2 +- .../docs/how-to/async-sql-encode-databases.md | 14 +- docs/en/docs/how-to/conditional-openapi.md | 2 +- docs/en/docs/how-to/configure-swagger-ui.md | 8 +- docs/en/docs/how-to/custom-docs-ui-assets.md | 14 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/en/docs/how-to/extending-openapi.md | 10 +- docs/en/docs/how-to/graphql.md | 2 +- .../docs/how-to/nosql-databases-couchbase.md | 16 +- .../docs/how-to/separate-openapi-schemas.md | 36 ++--- docs/en/docs/how-to/sql-databases-peewee.md | 34 ++-- docs/en/docs/python-types.md | 56 +++---- docs/en/docs/tutorial/background-tasks.md | 16 +- docs/en/docs/tutorial/bigger-applications.md | 30 ++-- docs/en/docs/tutorial/body-fields.md | 20 +-- docs/en/docs/tutorial/body-multiple-params.md | 44 +++--- docs/en/docs/tutorial/body-nested-models.md | 56 +++---- docs/en/docs/tutorial/body-updates.md | 24 +-- docs/en/docs/tutorial/body.md | 24 +-- docs/en/docs/tutorial/cookie-param-models.md | 16 +- docs/en/docs/tutorial/cookie-params.md | 20 +-- docs/en/docs/tutorial/cors.md | 2 +- docs/en/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 6 +- docs/en/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/en/docs/tutorial/encoder.md | 4 +- docs/en/docs/tutorial/extra-data-types.md | 20 +-- docs/en/docs/tutorial/extra-models.md | 20 +-- docs/en/docs/tutorial/first-steps.md | 14 +- docs/en/docs/tutorial/handling-errors.md | 16 +- docs/en/docs/tutorial/header-param-models.md | 24 +-- docs/en/docs/tutorial/header-params.md | 42 ++--- docs/en/docs/tutorial/metadata.md | 12 +- docs/en/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/en/docs/tutorial/path-params.md | 20 +-- docs/en/docs/tutorial/query-param-models.md | 24 +-- .../tutorial/query-params-str-validations.md | 142 ++++++++--------- docs/en/docs/tutorial/query-params.md | 20 +-- docs/en/docs/tutorial/request-files.md | 50 +++--- docs/en/docs/tutorial/request-form-models.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/en/docs/tutorial/request-forms.md | 12 +- docs/en/docs/tutorial/response-model.md | 68 ++++---- docs/en/docs/tutorial/response-status-code.md | 6 +- docs/en/docs/tutorial/schema-extra-example.md | 42 ++--- docs/en/docs/tutorial/security/first-steps.md | 18 +-- .../tutorial/security/get-current-user.md | 56 +++---- docs/en/docs/tutorial/security/oauth2-jwt.md | 40 ++--- .../docs/tutorial/security/simple-oauth2.md | 50 +++--- docs/en/docs/tutorial/sql-databases.md | 26 ++-- docs/en/docs/tutorial/static-files.md | 2 +- docs/en/docs/tutorial/testing.md | 18 +-- docs/en/mkdocs.yml | 1 - .../docs/advanced/additional-status-codes.md | 2 +- .../path-operation-advanced-configuration.md | 8 +- .../advanced/response-change-status-code.md | 2 +- docs/es/docs/advanced/response-directly.md | 4 +- docs/es/docs/advanced/response-headers.md | 4 +- docs/es/docs/how-to/graphql.md | 2 +- docs/es/docs/python-types.md | 26 ++-- docs/es/docs/tutorial/cookie-params.md | 20 +-- docs/es/docs/tutorial/first-steps.md | 16 +- docs/es/docs/tutorial/path-params.md | 18 +-- docs/es/docs/tutorial/query-params.md | 12 +- docs/fa/docs/advanced/sub-applications.md | 6 +- docs/fa/docs/tutorial/middleware.md | 4 +- docs/fr/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../path-operation-advanced-configuration.md | 16 +- docs/fr/docs/advanced/response-directly.md | 4 +- docs/fr/docs/python-types.md | 28 ++-- docs/fr/docs/tutorial/background-tasks.md | 8 +- docs/fr/docs/tutorial/body-multiple-params.md | 44 +++--- docs/fr/docs/tutorial/body.md | 12 +- docs/fr/docs/tutorial/debugging.md | 2 +- docs/fr/docs/tutorial/first-steps.md | 16 +- .../path-params-numeric-validations.md | 56 +++---- docs/fr/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/fr/docs/tutorial/query-params.md | 12 +- .../docs/advanced/additional-status-codes.md | 2 +- docs/ja/docs/advanced/custom-response.md | 24 +-- .../path-operation-advanced-configuration.md | 8 +- docs/ja/docs/advanced/response-directly.md | 4 +- docs/ja/docs/advanced/websockets.md | 10 +- docs/ja/docs/how-to/conditional-openapi.md | 2 +- docs/ja/docs/python-types.md | 28 ++-- docs/ja/docs/tutorial/background-tasks.md | 8 +- docs/ja/docs/tutorial/body-fields.md | 4 +- docs/ja/docs/tutorial/body-multiple-params.md | 10 +- docs/ja/docs/tutorial/body-nested-models.md | 22 +-- docs/ja/docs/tutorial/body-updates.md | 8 +- docs/ja/docs/tutorial/body.md | 12 +- docs/ja/docs/tutorial/cookie-params.md | 4 +- docs/ja/docs/tutorial/cors.md | 2 +- docs/ja/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 14 +- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 14 +- docs/ja/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 6 +- docs/ja/docs/tutorial/encoder.md | 2 +- docs/ja/docs/tutorial/extra-data-types.md | 4 +- docs/ja/docs/tutorial/extra-models.md | 10 +- docs/ja/docs/tutorial/first-steps.md | 16 +- docs/ja/docs/tutorial/handling-errors.md | 16 +- docs/ja/docs/tutorial/header-params.md | 8 +- docs/ja/docs/tutorial/metadata.md | 10 +- docs/ja/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 14 +- docs/ja/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/ja/docs/tutorial/query-params.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ja/docs/tutorial/request-forms.md | 4 +- docs/ja/docs/tutorial/response-model.md | 20 +-- docs/ja/docs/tutorial/response-status-code.md | 6 +- docs/ja/docs/tutorial/schema-extra-example.md | 6 +- docs/ja/docs/tutorial/security/first-steps.md | 6 +- .../tutorial/security/get-current-user.md | 12 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 8 +- docs/ja/docs/tutorial/static-files.md | 2 +- docs/ja/docs/tutorial/testing.md | 12 +- docs/ko/docs/advanced/events.md | 4 +- docs/ko/docs/python-types.md | 28 ++-- docs/ko/docs/tutorial/background-tasks.md | 10 +- docs/ko/docs/tutorial/body-fields.md | 20 +-- docs/ko/docs/tutorial/body-multiple-params.md | 10 +- docs/ko/docs/tutorial/body-nested-models.md | 22 +-- docs/ko/docs/tutorial/body.md | 24 +-- docs/ko/docs/tutorial/cookie-params.md | 20 +-- docs/ko/docs/tutorial/cors.md | 2 +- docs/ko/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/global-dependencies.md | 6 +- docs/ko/docs/tutorial/dependencies/index.md | 36 ++--- docs/ko/docs/tutorial/encoder.md | 2 +- docs/ko/docs/tutorial/extra-data-types.md | 20 +-- docs/ko/docs/tutorial/first-steps.md | 16 +- docs/ko/docs/tutorial/header-params.md | 8 +- docs/ko/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 14 +- docs/ko/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/ko/docs/tutorial/query-params.md | 12 +- docs/ko/docs/tutorial/request-files.md | 8 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ko/docs/tutorial/response-model.md | 20 +-- docs/ko/docs/tutorial/response-status-code.md | 6 +- docs/ko/docs/tutorial/schema-extra-example.md | 42 ++--- .../tutorial/security/get-current-user.md | 22 +-- .../docs/tutorial/security/simple-oauth2.md | 20 +-- docs/ko/docs/tutorial/static-files.md | 2 +- docs/nl/docs/python-types.md | 56 +++---- docs/pl/docs/tutorial/first-steps.md | 16 +- docs/pt/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../pt/docs/advanced/advanced-dependencies.md | 24 +-- docs/pt/docs/advanced/async-tests.md | 8 +- docs/pt/docs/advanced/behind-a-proxy.md | 10 +- docs/pt/docs/advanced/events.md | 12 +- docs/pt/docs/advanced/openapi-webhooks.md | 2 +- .../advanced/response-change-status-code.md | 2 +- docs/pt/docs/advanced/response-directly.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/pt/docs/advanced/settings.md | 36 ++--- docs/pt/docs/advanced/sub-applications.md | 6 +- docs/pt/docs/advanced/templates.md | 8 +- docs/pt/docs/advanced/testing-dependencies.md | 10 +- docs/pt/docs/advanced/testing-events.md | 2 +- docs/pt/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/pt/docs/advanced/wsgi.md | 2 +- docs/pt/docs/how-to/conditional-openapi.md | 2 +- docs/pt/docs/how-to/configure-swagger-ui.md | 8 +- docs/pt/docs/how-to/graphql.md | 2 +- docs/pt/docs/python-types.md | 28 ++-- docs/pt/docs/tutorial/background-tasks.md | 8 +- docs/pt/docs/tutorial/bigger-applications.md | 30 ++-- docs/pt/docs/tutorial/body-fields.md | 4 +- docs/pt/docs/tutorial/body-multiple-params.md | 20 +-- docs/pt/docs/tutorial/body-nested-models.md | 22 +-- docs/pt/docs/tutorial/body.md | 12 +- docs/pt/docs/tutorial/cookie-params.md | 20 +-- docs/pt/docs/tutorial/cors.md | 2 +- docs/pt/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 6 +- docs/pt/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/pt/docs/tutorial/encoder.md | 4 +- docs/pt/docs/tutorial/extra-data-types.md | 4 +- docs/pt/docs/tutorial/extra-models.md | 20 +-- docs/pt/docs/tutorial/first-steps.md | 16 +- docs/pt/docs/tutorial/handling-errors.md | 14 +- docs/pt/docs/tutorial/header-params.md | 18 +-- docs/pt/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 18 +-- docs/pt/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/pt/docs/tutorial/query-params.md | 20 +-- docs/pt/docs/tutorial/request-form-models.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/pt/docs/tutorial/request-forms.md | 4 +- docs/pt/docs/tutorial/request_files.md | 50 +++--- docs/pt/docs/tutorial/response-status-code.md | 6 +- docs/pt/docs/tutorial/schema-extra-example.md | 8 +- docs/pt/docs/tutorial/security/first-steps.md | 6 +- docs/pt/docs/tutorial/static-files.md | 2 +- docs/pt/docs/tutorial/testing.md | 18 +-- docs/ru/docs/python-types.md | 28 ++-- docs/ru/docs/tutorial/background-tasks.md | 10 +- docs/ru/docs/tutorial/body-fields.md | 8 +- docs/ru/docs/tutorial/body-multiple-params.md | 44 +++--- docs/ru/docs/tutorial/body-nested-models.md | 56 +++---- docs/ru/docs/tutorial/body-updates.md | 24 +-- docs/ru/docs/tutorial/body.md | 12 +- docs/ru/docs/tutorial/cookie-params.md | 8 +- docs/ru/docs/tutorial/cors.md | 2 +- docs/ru/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 22 +-- .../dependencies/global-dependencies.md | 6 +- docs/ru/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/ru/docs/tutorial/encoder.md | 4 +- docs/ru/docs/tutorial/extra-data-types.md | 8 +- docs/ru/docs/tutorial/extra-models.md | 20 +-- docs/ru/docs/tutorial/first-steps.md | 16 +- docs/ru/docs/tutorial/handling-errors.md | 16 +- docs/ru/docs/tutorial/header-params.md | 42 ++--- docs/ru/docs/tutorial/metadata.md | 10 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/ru/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 146 +++++++++--------- docs/ru/docs/tutorial/query-params.md | 20 +-- docs/ru/docs/tutorial/request-files.md | 50 +++--- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/ru/docs/tutorial/request-forms.md | 12 +- docs/ru/docs/tutorial/response-model.md | 68 ++++---- docs/ru/docs/tutorial/response-status-code.md | 6 +- docs/ru/docs/tutorial/schema-extra-example.md | 28 ++-- docs/ru/docs/tutorial/security/first-steps.md | 18 +-- docs/ru/docs/tutorial/static-files.md | 2 +- docs/ru/docs/tutorial/testing.md | 18 +-- docs/tr/docs/advanced/testing-websockets.md | 2 +- docs/tr/docs/advanced/wsgi.md | 2 +- docs/tr/docs/python-types.md | 28 ++-- docs/tr/docs/tutorial/cookie-params.md | 20 +-- docs/tr/docs/tutorial/first-steps.md | 16 +- docs/tr/docs/tutorial/path-params.md | 20 +-- docs/tr/docs/tutorial/query-params.md | 20 +-- docs/tr/docs/tutorial/request-forms.md | 12 +- docs/tr/docs/tutorial/static-files.md | 2 +- docs/uk/docs/python-types.md | 48 +++--- docs/uk/docs/tutorial/body-fields.md | 20 +-- docs/uk/docs/tutorial/body.md | 24 +-- docs/uk/docs/tutorial/cookie-params.md | 20 +-- docs/uk/docs/tutorial/encoder.md | 4 +- docs/uk/docs/tutorial/extra-data-types.md | 20 +-- docs/uk/docs/tutorial/first-steps.md | 14 +- docs/vi/docs/python-types.md | 56 +++---- docs/vi/docs/tutorial/first-steps.md | 16 +- docs/zh/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../zh/docs/advanced/advanced-dependencies.md | 8 +- docs/zh/docs/advanced/behind-a-proxy.md | 8 +- docs/zh/docs/advanced/custom-response.md | 22 +-- docs/zh/docs/advanced/dataclasses.md | 6 +- docs/zh/docs/advanced/events.md | 4 +- docs/zh/docs/advanced/generate-clients.md | 14 +- docs/zh/docs/advanced/middleware.md | 6 +- docs/zh/docs/advanced/openapi-callbacks.md | 8 +- .../path-operation-advanced-configuration.md | 8 +- .../advanced/response-change-status-code.md | 2 +- docs/zh/docs/advanced/response-cookies.md | 4 +- docs/zh/docs/advanced/response-directly.md | 4 +- docs/zh/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 16 +- docs/zh/docs/advanced/settings.md | 32 ++-- docs/zh/docs/advanced/sub-applications.md | 6 +- docs/zh/docs/advanced/templates.md | 8 +- docs/zh/docs/advanced/testing-database.md | 8 +- docs/zh/docs/advanced/testing-dependencies.md | 2 +- docs/zh/docs/advanced/testing-events.md | 2 +- docs/zh/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/zh/docs/advanced/websockets.md | 20 +-- docs/zh/docs/advanced/wsgi.md | 2 +- docs/zh/docs/how-to/configure-swagger-ui.md | 8 +- docs/zh/docs/python-types.md | 26 ++-- docs/zh/docs/tutorial/background-tasks.md | 16 +- docs/zh/docs/tutorial/bigger-applications.md | 26 ++-- docs/zh/docs/tutorial/body-fields.md | 20 +-- docs/zh/docs/tutorial/body-multiple-params.md | 44 +++--- docs/zh/docs/tutorial/body-nested-models.md | 56 +++---- docs/zh/docs/tutorial/body-updates.md | 8 +- docs/zh/docs/tutorial/body.md | 24 +-- docs/zh/docs/tutorial/cookie-params.md | 20 +-- docs/zh/docs/tutorial/cors.md | 2 +- docs/zh/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 2 +- docs/zh/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 6 +- docs/zh/docs/tutorial/encoder.md | 4 +- docs/zh/docs/tutorial/extra-data-types.md | 20 +-- docs/zh/docs/tutorial/extra-models.md | 20 +-- docs/zh/docs/tutorial/first-steps.md | 16 +- docs/zh/docs/tutorial/handling-errors.md | 16 +- docs/zh/docs/tutorial/header-params.md | 42 ++--- docs/zh/docs/tutorial/metadata.md | 10 +- docs/zh/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 30 ++-- docs/zh/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 36 ++--- docs/zh/docs/tutorial/query-params.md | 20 +-- docs/zh/docs/tutorial/request-files.md | 20 +-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/zh/docs/tutorial/request-forms.md | 4 +- docs/zh/docs/tutorial/response-model.md | 30 ++-- docs/zh/docs/tutorial/response-status-code.md | 6 +- docs/zh/docs/tutorial/schema-extra-example.md | 18 +-- docs/zh/docs/tutorial/security/first-steps.md | 10 +- .../tutorial/security/get-current-user.md | 12 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 32 ++-- .../docs/tutorial/security/simple-oauth2.md | 10 +- docs/zh/docs/tutorial/sql-databases.md | 74 ++++----- docs/zh/docs/tutorial/static-files.md | 2 +- docs/zh/docs/tutorial/testing.md | 18 +-- 529 files changed, 4747 insertions(+), 4748 deletions(-) diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index d5304a65e..4a602b679 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -23,7 +23,7 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` এই প্রোগ্রামটি কল করলে আউটপুট হয়: @@ -39,7 +39,7 @@ John Doe * তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### এটি সম্পাদনা করুন @@ -83,7 +83,7 @@ John Doe এগুলিই "টাইপ হিন্ট": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: @@ -113,7 +113,7 @@ John Doe এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: @@ -123,7 +123,7 @@ John Doe এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## টাইপ ঘোষণা @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### টাইপ প্যারামিটার সহ জেনেরিক টাইপ @@ -182,7 +182,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: ``` Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। @@ -202,7 +202,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন। ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও। @@ -333,7 +333,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.8+ বিকল্প ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` `name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: @@ -388,7 +388,7 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 @@ -452,13 +452,13 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: @@ -486,7 +486,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python-এ এমন একটি ফিচার আছে যা `Annotated` Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ Python 3.9-এর নীচের সংস্করণগুলিতে, আ এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 6f2c4b2dd..a87c56491 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note | "Hinweis" @@ -178,7 +178,7 @@ Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientyp Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note | "Hinweis" @@ -208,7 +208,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: @@ -244,7 +244,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper Zum Beispiel: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## Weitere Informationen zu OpenAPI-Responses diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index 672efee51..fc8d09e4c 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -17,7 +17,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.10+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index f29970872..54351714e 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ Dazu deklarieren wir eine Methode `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Dazu deklarieren wir eine Methode `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu dekl //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu dekl //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ Wir könnten eine Instanz dieser Klasse erstellen mit: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ Wir könnten eine Instanz dieser Klasse erstellen mit: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index e56841faa..93ff84b8a 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ Die Datei `main.py` hätte als Inhalt: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Es ausführen @@ -61,7 +61,7 @@ $ pytest Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip | "Tipp" @@ -73,7 +73,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` Das ist das Äquivalent zu: diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 18f90ebde..74b25308a 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1 Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. @@ -99,7 +99,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Wenn Sie Uvicorn dann starten mit: @@ -128,7 +128,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -310,7 +310,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es Zum Beispiel: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Erzeugt ein OpenAPI-Schema, wie: @@ -359,7 +359,7 @@ Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 20d6a039a..357d2c562 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning | "Achtung" @@ -104,7 +104,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -145,7 +145,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -181,7 +181,7 @@ Eine alternative JSON-Response mit `dataclasses`: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. @@ -35,7 +35,7 @@ Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Tr Sie können `dataclasses` auch im Parameter `response_model` verwenden: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. @@ -53,7 +53,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. Wir importieren `field` weiterhin von Standard-`dataclasses`. diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index e898db49b..b0c4d3922 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -31,7 +31,7 @@ Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. @@ -51,7 +51,7 @@ Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. @@ -65,7 +65,7 @@ Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: @@ -89,7 +89,7 @@ In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergebe Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Alternative Events (deprecated) @@ -113,7 +113,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. @@ -127,7 +127,7 @@ Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandle Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index b8d66fdd7..80c44b3f9 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -31,7 +31,7 @@ Beginnen wir mit einer einfachen FastAPI-Anwendung: //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -39,7 +39,7 @@ Beginnen wir mit einer einfachen FastAPI-Anwendung: //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -150,7 +150,7 @@ Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen w //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -158,7 +158,7 @@ Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen w //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -211,7 +211,7 @@ Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `gener //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -219,7 +219,7 @@ Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `gener //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -247,7 +247,7 @@ Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dan //// tab | Python ```Python -{!> ../../../docs_src/generate_clients/tutorial004.py!} +{!> ../../docs_src/generate_clients/tutorial004.py!} ``` //// @@ -255,7 +255,7 @@ Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dan //// tab | Node.js ```Javascript -{!> ../../../docs_src/generate_clients/tutorial004.js!} +{!> ../../docs_src/generate_clients/tutorial004.js!} ``` //// diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 8912225fb..b4001efda 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -58,7 +58,7 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` Die folgenden Argumente werden unterstützt: @@ -82,7 +82,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` Die folgenden Argumente werden unterstützt: diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index d7b5bc885..f407d5450 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "Tipp" @@ -93,7 +93,7 @@ Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehme Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Die Callback-*Pfadoperation* erstellen @@ -106,7 +106,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -176,7 +176,7 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "Tipp" diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index fb0daa908..9f1bb6959 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.9 Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index c9cb82fe3..2d8b88be5 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -23,7 +23,7 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | "Tipp" @@ -45,7 +45,7 @@ Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Fortgeschrittene Beschreibung mittels Docstring @@ -57,7 +57,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## Zusätzliche Responses @@ -101,7 +101,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -150,7 +150,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: ```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -168,7 +168,7 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v2 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -176,7 +176,7 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v1 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// @@ -196,7 +196,7 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v2 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -204,7 +204,7 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v1 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index bba908a3e..202df0d87 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 3d2043565..ba100870d 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -27,7 +27,7 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip | "Tipp" diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 377490b56..70c045f57 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Technische Details" @@ -57,7 +57,7 @@ Nehmen wir an, Sie möchten eine ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser di //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index f02707698..c0af2560a 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.10+ ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.9+ ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.8+ ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.10+ ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.9+ ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.8+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="61-64" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.10+ ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.9+ ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.8+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="154" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.10+ ```Python hl_lines="4 139 170" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.9+ ```Python hl_lines="4 139 170" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.8+ ```Python hl_lines="4 140 171" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 138 167" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.10+ ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.9+ ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.8+ ```Python hl_lines="8 106" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 104" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.10+ ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.9+ ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.8+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="104 106-114" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.10+ ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.9+ ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.8+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="45 115-126" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.10+ ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.9+ ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.8+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="127-133" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index 3cd4c6c7d..8b9ba2f48 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -181,7 +181,7 @@ Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -195,7 +195,7 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -215,7 +215,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Den Server ausführen @@ -251,13 +251,13 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` Und dann verwenden Sie diese in einer Datei `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip | "Tipp" @@ -277,7 +277,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -289,7 +289,7 @@ Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurüc //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -297,7 +297,7 @@ Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurüc //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -311,7 +311,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -329,7 +329,7 @@ Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einf //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -337,7 +337,7 @@ Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einf //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -351,7 +351,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -361,7 +361,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -406,7 +406,7 @@ Und dann aktualisieren Sie Ihre `config.py` mit: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// tip | "Tipp" @@ -420,7 +420,7 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// tip | "Tipp" @@ -465,7 +465,7 @@ Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Obj //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -473,7 +473,7 @@ Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Obj //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -487,7 +487,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 7dfaaa0cd..172b8d3c1 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Unteranwendung @@ -21,7 +21,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Die Unteranwendung mounten @@ -31,7 +31,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index abc7624f1..6cb3fcf6c 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note | "Hinweis" @@ -58,7 +58,7 @@ Sie können auch `from starlette.templating import Jinja2Templates` verwenden. Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template-Kontextwerte @@ -112,13 +112,13 @@ Mit beispielsweise der ID `42` würde dies Folgendes ergeben: Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index f131d27cd..c565b30f2 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index f50093548..3e63791c6 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 4cbc45c17..7ae7d92d6 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Hinweis" diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index 1d575a7cb..6a0b96680 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado Dazu müssen Sie direkt auf den Request zugreifen. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index 6d772b6c9..cf13fa23c 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -39,7 +39,7 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## Einen `websocket` erstellen @@ -47,7 +47,7 @@ Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "Technische Details" @@ -63,7 +63,7 @@ Sie können auch `from starlette.websockets import WebSocket` verwenden. In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -118,7 +118,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -126,7 +126,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -134,7 +134,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -148,7 +148,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -213,7 +213,7 @@ Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_ //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -221,7 +221,7 @@ Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_ //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 19ff90a90..50abc84d1 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Es ansehen diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md index 7f277bb88..a0a4983bb 100644 --- a/docs/de/docs/how-to/conditional-openapi.md +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener Zum Beispiel: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index 7d62a14d3..31b9cd290 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: @@ -31,7 +31,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: @@ -45,7 +45,7 @@ FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anw Es umfasst die folgenden Defaultkonfigurationen: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. @@ -53,7 +53,7 @@ Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_paramet Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Andere Parameter der Swagger-Oberfläche diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index e8750f7c2..e5fd20a10 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -19,7 +19,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -37,7 +37,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... ```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` /// tip | "Tipp" @@ -55,7 +55,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Es ausprobieren @@ -125,7 +125,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. ```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die statischen Dateien testen @@ -159,7 +159,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -177,7 +177,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... ```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` /// tip | "Tipp" @@ -195,7 +195,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index a0c4a0e0c..f81fa1da3 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -57,7 +57,7 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "Technische Details" @@ -97,13 +97,13 @@ Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf de Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Benutzerdefinierte `APIRoute`-Klasse in einem Router @@ -111,11 +111,11 @@ Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im G Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 347c5bed3..c895fb860 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -44,7 +44,7 @@ Fügen wir beispielsweise Strawberry-Dokumentation. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index eaecb27de..974341dd2 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -13,7 +13,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} # Code unterhalb weggelassen 👇 ``` @@ -22,7 +22,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ```
@@ -32,7 +32,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} # Code unterhalb weggelassen 👇 ``` @@ -41,7 +41,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ```
@@ -51,7 +51,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} # Code unterhalb weggelassen 👇 ``` @@ -60,7 +60,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ```
@@ -74,7 +74,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} # Code unterhalb weggelassen 👇 ``` @@ -83,7 +83,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ```
@@ -93,7 +93,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} # Code unterhalb weggelassen 👇 ``` @@ -102,7 +102,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ```
@@ -112,7 +112,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} # Code unterhalb weggelassen 👇 ``` @@ -121,7 +121,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ```
@@ -145,7 +145,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` //// @@ -153,7 +153,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` //// @@ -161,7 +161,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` //// @@ -226,7 +226,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} ``` //// @@ -234,7 +234,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} ``` //// @@ -242,7 +242,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} ``` //// diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index 9bbff83d3..a43bf5ffe 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -23,7 +23,7 @@ Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, üb Fangen wir mit einem einfachen Beispiel an: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Dieses Programm gibt aus: @@ -39,7 +39,7 @@ Die Funktion macht Folgendes: * Verkettet sie mit einem Leerzeichen in der Mitte. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Bearbeiten Sie es @@ -83,7 +83,7 @@ Das war's. Das sind die „Typhinweise“: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: @@ -113,7 +113,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: @@ -123,7 +123,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Deklarieren von Typen @@ -144,7 +144,7 @@ Zum Beispiel diese: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generische Typen mit Typ-Parametern @@ -182,7 +182,7 @@ Als Typ nehmen Sie `list`. Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckige Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). @@ -202,7 +202,7 @@ Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Men //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Men //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Der zweite Typ-Parameter ist für die Werte des `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Der zweite Typ-Parameter ist für die Werte des `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die mö //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die mö //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. @@ -333,7 +333,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.8+ Alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie Nehmen wir zum Beispiel diese Funktion: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: @@ -388,7 +388,7 @@ say_hi(name=None) # Das funktioniert, None is gültig 🎉 Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 @@ -452,13 +452,13 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren. Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Dann können Sie eine Variable vom Typ `Person` deklarieren: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Und wiederum bekommen Sie die volle Editor-Unterstützung: @@ -486,7 +486,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_ex Es wird bereits mit **FastAPI** installiert sein. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index 0852288d5..cd857f5e7 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -34,7 +34,7 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Den Hintergrundtask hinzufügen @@ -42,7 +42,7 @@ Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir di Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` erhält als Argumente: @@ -60,7 +60,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md index 986a99a38..000fa1f43 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen. Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Pfadoperationen* mit `APIRouter` @@ -96,7 +96,7 @@ Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren. Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen. @@ -124,7 +124,7 @@ Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefiniert //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefiniert //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben: Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in: @@ -243,7 +243,7 @@ Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` impo Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### Wie relative Importe funktionieren @@ -316,7 +316,7 @@ Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperat Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip | "Tipp" @@ -344,7 +344,7 @@ Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse. Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Den `APIRouter` importieren @@ -352,7 +352,7 @@ Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies Jetzt importieren wir die anderen Submodule, die `APIRouter` haben: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren. @@ -417,7 +417,7 @@ würde der `router` von `users` den von `items` überschreiben und wir könnten Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` @@ -426,7 +426,7 @@ Um also beide in derselben Datei verwenden zu können, importieren wir die Submo Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -468,7 +468,7 @@ Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, di In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen. @@ -476,7 +476,7 @@ Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wi Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können. @@ -499,7 +499,7 @@ Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen. Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index 33f7713ee..d22524c67 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ Importieren Sie es zuerst: //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie es zuerst: //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie es zuerst: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 977e17671..26ae73ebc 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ Zum Beispiel: //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Zum Beispiel: //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Zum Beispiel: //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ so wie in: //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ so wie in: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ so wie in: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 8aef965f4..13153aa68 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list` //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list` //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Eine `list`e mit einem Typ-Parameter deklarieren @@ -68,7 +68,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ so wie in: //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ so wie in: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüs //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüs //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index b83554914..ed5c1890f 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.8+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -87,7 +87,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -95,7 +95,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -103,7 +103,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.8+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -125,7 +125,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -133,7 +133,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -141,7 +141,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.8+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -164,7 +164,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -180,7 +180,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.8+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 3fdd4ade3..3a64e747e 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -25,7 +25,7 @@ Zuerst müssen Sie `BaseModel` von `pydantic` importieren: //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ Zuerst müssen Sie `BaseModel` von `pydantic` importieren: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ Verwenden Sie Standard-Python-Typen für die Klassenattribute: //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Verwenden Sie Standard-Python-Typen für die Klassenattribute: //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index 0060db8e8..4714a59ae 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md index 0a9f05bf9..a660ab337 100644 --- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 47d6453c2..3bb261e44 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ Es sollte eine `list`e von `Depends()` sein: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Es sollte eine `list`e von `Depends()` sein: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhä //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhä //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeit //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeit //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Si //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Si //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md index 9c2e6dd86..48b057e28 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird: ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Response gesendet wurde: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Tipp" @@ -64,7 +64,7 @@ Sie können also mit `except SomeException` diese bestimmte Exception innerhalb Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Unterabhängigkeiten mit `yield`. @@ -78,7 +78,7 @@ Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `de //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `de //// tab | Python 3.8+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` //// tab | Python 3.8+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓 //// tab | Python 3.9+ ```Python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓 //// tab | Python 3.8+ ```Python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ In Python können Sie Kontextmanager erstellen, indem Sie ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md index f7d9ed510..494708d19 100644 --- a/docs/de/docs/tutorial/dependencies/index.md +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -33,7 +33,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -41,7 +41,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -49,7 +49,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -63,7 +63,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -77,7 +77,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -115,7 +115,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -123,7 +123,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -131,7 +131,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -145,7 +145,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -159,7 +159,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -171,7 +171,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -179,7 +179,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -187,7 +187,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -201,7 +201,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -215,7 +215,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -278,7 +278,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -286,7 +286,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -294,7 +294,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 12664a8cd..a20aed63b 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 38a881b4f..0ab72b8dd 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-k //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-k //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md index 334a232a8..7581b4f87 100644 --- a/docs/de/docs/tutorial/extra-data-types.md +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index cfd0230eb..14e842065 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen kön //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen kön //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -179,7 +179,7 @@ Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -187,7 +187,7 @@ Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -209,7 +209,7 @@ Listen Sie, wenn Sie eine ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -217,7 +217,7 @@ Listen Sie, wenn Sie eine ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -245,7 +245,7 @@ Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3 //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -253,7 +253,7 @@ Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3 //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -269,7 +269,7 @@ In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3. //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -277,7 +277,7 @@ In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3. //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index b9e38707c..fe3886b70 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Die einfachste FastAPI-Datei könnte wie folgt aussehen: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Kopieren Sie dies in eine Datei `main.py`. @@ -134,7 +134,7 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier ### Schritt 1: Importieren von `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. @@ -150,7 +150,7 @@ Sie können alle ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Header`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md index 3ab56ff3e..98724e1e8 100644 --- a/docs/de/docs/tutorial/metadata.md +++ b/docs/de/docs/tutorial/metadata.md @@ -19,7 +19,7 @@ Sie können die folgenden Felder festlegen, welche in der OpenAPI-Spezifikation Sie können diese wie folgt setzen: ```Python hl_lines="3-16 19-32" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip | "Tipp" @@ -39,7 +39,7 @@ Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit ei Zum Beispiel: ```Python hl_lines="31" -{!../../../docs_src/metadata/tutorial001_1.py!} +{!../../docs_src/metadata/tutorial001_1.py!} ``` ## Metadaten für Tags @@ -63,7 +63,7 @@ Versuchen wir das an einem Beispiel mit Tags für `users` und `items`. Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter `openapi_tags`: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt. @@ -79,7 +79,7 @@ Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -109,7 +109,7 @@ Sie können das aber mit dem Parameter `openapi_url` konfigurieren. Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden. @@ -128,5 +128,5 @@ Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurie Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md index 62a0d1613..410dc0247 100644 --- a/docs/de/docs/tutorial/middleware.md +++ b/docs/de/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ Die Middleware-Funktion erhält: * Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "Tipp" @@ -60,7 +60,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## Andere Middlewares diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 03980b7dd..411916e9c 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. **FastAPI** unterstützt diese genauso wie einfache Strings: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Zusammenfassung und Beschreibung @@ -101,7 +101,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolg Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden: diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md index 3908a0b2d..fc2d5dff1 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -167,7 +167,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -177,7 +177,7 @@ Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` ver //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -185,7 +185,7 @@ Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` ver //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -214,7 +214,7 @@ Wenn Sie eines der folgenden Dinge tun möchten: Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als kwargs, verwendet werden. Selbst wenn diese keinen Defaultwert haben. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Besser mit `Annotated` @@ -224,7 +224,7 @@ Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht hab //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -232,7 +232,7 @@ Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht hab //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -245,7 +245,7 @@ Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die g //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -253,7 +253,7 @@ Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die g //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -267,7 +267,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -282,7 +282,7 @@ Das Gleiche trifft zu auf: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -290,7 +290,7 @@ Das Gleiche trifft zu auf: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -304,7 +304,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -322,7 +322,7 @@ Das gleiche gilt für lt ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -330,7 +330,7 @@ Das gleiche gilt für lt ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -344,7 +344,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md index 2c1b691a8..9cb172c94 100644 --- a/docs/de/docs/tutorial/path-params.md +++ b/docs/de/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben. @@ -19,7 +19,7 @@ Wenn Sie dieses Beispiel ausführen und auf ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ Nehmen wir als Beispiel die folgende Anwendung: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ Importieren Sie zuerst: In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions Es wird bereits mit FastAPI installiert sein. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -126,7 +126,7 @@ Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Qu //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -134,7 +134,7 @@ Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Qu //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -164,7 +164,7 @@ So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, de //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, de //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -278,7 +278,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -286,7 +286,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -294,7 +294,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -308,7 +308,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -322,7 +322,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -334,7 +334,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -342,7 +342,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -350,7 +350,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -364,7 +364,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -378,7 +378,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -402,7 +402,7 @@ Sie könnten immer noch Code sehen, der den alten Namen verwendet: //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} ``` //// @@ -418,7 +418,7 @@ Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -426,7 +426,7 @@ Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -440,7 +440,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -488,7 +488,7 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -496,7 +496,7 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -510,7 +510,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip | "Tipp" @@ -530,7 +530,7 @@ Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich is //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -538,7 +538,7 @@ Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich is //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -552,7 +552,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -576,7 +576,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -584,7 +584,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -592,7 +592,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -606,7 +606,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -620,7 +620,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -646,7 +646,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -654,7 +654,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -662,7 +662,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -676,7 +676,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -690,7 +690,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -704,7 +704,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -745,7 +745,7 @@ Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übe //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -753,7 +753,7 @@ Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übe //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -767,7 +767,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -781,7 +781,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -810,7 +810,7 @@ Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[s //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -818,7 +818,7 @@ Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[s //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -832,7 +832,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -864,7 +864,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -872,7 +872,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -880,7 +880,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -894,7 +894,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -908,7 +908,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -918,7 +918,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -926,7 +926,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -934,7 +934,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -948,7 +948,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -962,7 +962,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -988,7 +988,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -996,7 +996,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1004,7 +1004,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1018,7 +1018,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1032,7 +1032,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1048,7 +1048,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1056,7 +1056,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1064,7 +1064,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1078,7 +1078,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1092,7 +1092,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1108,7 +1108,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1116,7 +1116,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1124,7 +1124,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1138,7 +1138,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1152,7 +1152,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index 136852216..bb1dbdf9c 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. @@ -66,7 +66,7 @@ Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem S //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem S //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -150,7 +150,7 @@ Parameter werden anhand ihres Namens erkannt: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -158,7 +158,7 @@ Parameter werden anhand ihres Namens erkannt: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. @@ -222,7 +222,7 @@ Und natürlich können Sie einige Parameter als erforderlich, einige mit Default //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -230,7 +230,7 @@ Und natürlich können Sie einige Parameter als erforderlich, einige mit Default //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index cf44df5f0..c0d0ef3f2 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -19,7 +19,7 @@ Importieren Sie `File` und `UploadFile` von `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Importieren Sie `File` und `UploadFile` von `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen w //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen w //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel z //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel z //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu se //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu se //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index e109595d1..2b89edbb4 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -15,7 +15,7 @@ Z. B. `pip install python-multipart`. //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -23,7 +23,7 @@ Z. B. `pip install python-multipart`. //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -37,7 +37,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -49,7 +49,7 @@ Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Q //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -57,7 +57,7 @@ Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Q //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -71,7 +71,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 391788aff..0784aa8c0 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ Importieren Sie `Form` von `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie `Form` von `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` mach //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` mach //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index b480780bc..31ad73c77 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -143,7 +143,7 @@ Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -175,7 +175,7 @@ Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Aus //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Aus //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -193,7 +193,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -201,7 +201,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -211,7 +211,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -219,7 +219,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -249,7 +249,7 @@ Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil a //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -257,7 +257,7 @@ Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil a //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -303,7 +303,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. @@ -315,7 +315,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch ` Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. @@ -329,7 +329,7 @@ Das gleiche wird passieren, wenn Sie eine ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -355,7 +355,7 @@ In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -363,7 +363,7 @@ In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -377,7 +377,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -385,7 +385,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -393,7 +393,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -413,7 +413,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -421,7 +421,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -429,7 +429,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -532,7 +532,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -540,7 +540,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -560,7 +560,7 @@ Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ei //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -568,7 +568,7 @@ Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ei //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index 5f96b83e4..872007a12 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo * usw. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Hinweis" @@ -77,7 +77,7 @@ Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Si Schauen wir uns das vorherige Beispiel noch einmal an: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` ist der Statuscode für „Created“ („Erzeugt“). @@ -87,7 +87,7 @@ Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet. Sie können die Hilfsvariablen von `fastapi.status` verwenden. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden: diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index 07b4bb759..0da1a4ea4 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.10+ Pydantic v2 ```Python hl_lines="13-24" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusät //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusät //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ Sie können es so verwenden: //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ Sie können es so verwenden: //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ Sie können es so verwenden: //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 6bc42cf6c..c552a681b 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -157,7 +157,7 @@ Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wi //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wi //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -223,7 +223,7 @@ Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -231,7 +231,7 @@ Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -245,7 +245,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 8a68deeef..a9478a36e 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -5,7 +5,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injectio //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -13,7 +13,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injectio //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -27,7 +27,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -45,7 +45,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.10+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -53,7 +53,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.9+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.8+ ```Python hl_lines="5 13-17" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -89,7 +89,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.10+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -115,7 +115,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.9+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -123,7 +123,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.8+ ```Python hl_lines="26" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -137,7 +137,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -163,7 +163,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -171,7 +171,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ ```Python hl_lines="20-23 27-28" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -193,7 +193,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -207,7 +207,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -219,7 +219,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.10+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -227,7 +227,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.9+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -235,7 +235,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.8+ ```Python hl_lines="32" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -249,7 +249,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -263,7 +263,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -323,7 +323,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.10+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.9+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.8+ ```Python hl_lines="31-33" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -353,7 +353,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -367,7 +367,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 88f0dbe42..79e817840 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -121,7 +121,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.10+ ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -129,7 +129,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.9+ ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -137,7 +137,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.8+ ```Python hl_lines="7 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -151,7 +151,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -165,7 +165,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -207,7 +207,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.10+ ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -215,7 +215,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.9+ ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -223,7 +223,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.8+ ```Python hl_lines="6 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -237,7 +237,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -251,7 +251,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -267,7 +267,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.10+ ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -275,7 +275,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.9+ ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -283,7 +283,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.8+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -297,7 +297,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="88-105" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -311,7 +311,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -325,7 +325,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.10+ ```Python hl_lines="117-132" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -333,7 +333,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.9+ ```Python hl_lines="117-132" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -341,7 +341,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.8+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -355,7 +355,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="114-129" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -369,7 +369,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 3b1c4ae28..4c20fae55 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.10+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -63,7 +63,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.9+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -71,7 +71,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.8+ ```Python hl_lines="4 79" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -85,7 +85,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -99,7 +99,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -153,7 +153,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.10+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -161,7 +161,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.9+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -169,7 +169,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.8+ ```Python hl_lines="3 80-82" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -197,7 +197,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.10+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.9+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.8+ ```Python hl_lines="83-86" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -321,7 +321,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.10+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -329,7 +329,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.9+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -337,7 +337,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.8+ ```Python hl_lines="88" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -351,7 +351,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -365,7 +365,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -397,7 +397,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.10+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -405,7 +405,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.9+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -413,7 +413,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.8+ ```Python hl_lines="59-67 70-75 95" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -427,7 +427,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="56-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -441,7 +441,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index cca8cd0ea..4afd251aa 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Technische Details" diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 43ced2aae..bda6d7d60 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -27,7 +27,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Tipp" @@ -75,7 +75,7 @@ In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Testdatei @@ -93,7 +93,7 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ... und haben den Code für die Tests wie zuvor. @@ -125,7 +125,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -133,7 +133,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -141,7 +141,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -155,7 +155,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index 7a70718c5..e4442135e 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note @@ -178,7 +178,7 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note @@ -208,7 +208,7 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -244,7 +244,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 3f3b0aea4..7a50e1bca 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index 22044c783..721428ce4 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -19,7 +19,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: ```Python hl_lines="10" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -29,7 +29,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: ```Python hl_lines="7" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -39,7 +39,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: ```Python hl_lines="16" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -57,7 +57,7 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: ```Python hl_lines="20" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` /// tip diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 11f885fe6..4d468acd4 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ 📁 `main.py` 🔜 ✔️: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## 🏃 ⚫️ @@ -61,7 +61,7 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip @@ -73,7 +73,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` 👉 🌓: diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index bb65e1487..e66ddccf7 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -95,7 +95,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -124,7 +124,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -306,7 +306,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` 🔜 🏗 🗄 🔗 💖: @@ -355,7 +355,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index eec87b91b..7147a4536 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning @@ -104,7 +104,7 @@ 🖼, ⚫️ 💪 🕳 💖: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -145,7 +145,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -181,7 +181,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip @@ -197,7 +197,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` --- @@ -206,7 +206,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} +{!../../docs_src/custom_response/tutorial006b.py!} ``` 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -218,7 +218,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} +{!../../docs_src/custom_response/tutorial006c.py!} ``` ### `StreamingResponse` @@ -226,7 +226,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -238,7 +238,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘. @@ -269,13 +269,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` 👆 💪 ⚙️ `response_class` 🔢: ```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} +{!../../docs_src/custom_response/tutorial009b.py!} ``` 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -291,7 +291,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: ```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} +{!../../docs_src/custom_response/tutorial009c.py!} ``` 🔜 ↩️ 🛬: @@ -319,7 +319,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index 3f49ef07c..ab76e5083 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -5,7 +5,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` 👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. @@ -35,7 +35,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` 🎻 🔜 🔁 🗜 Pydantic 🎻. @@ -53,7 +53,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`. diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 12c902c18..2eae2b366 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -31,7 +31,7 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. @@ -51,7 +51,7 @@ 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -65,7 +65,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -89,7 +89,7 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## 🎛 🎉 (😢) @@ -113,7 +113,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -127,7 +127,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index c8e044340..f09d75623 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -139,7 +139,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -147,7 +147,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -200,7 +200,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -208,7 +208,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -234,7 +234,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: ```Python -{!../../../docs_src/generate_clients/tutorial004.py!} +{!../../docs_src/generate_clients/tutorial004.py!} ``` ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index e3cc389c6..23d2918d7 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -58,7 +58,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` 📄 ❌ 🐕‍🦺: @@ -82,7 +82,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` 📄 ❌ 🐕‍🦺: diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 00d54ebec..f7b5e7ed9 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip @@ -93,7 +93,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### ✍ ⏲ *➡ 🛠️* @@ -106,7 +106,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -176,7 +176,7 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index b684df26f..805bfdf30 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -23,7 +23,7 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## 🏧 📛 ⚪️➡️ #️⃣ @@ -57,7 +57,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## 🌖 📨 @@ -101,7 +101,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -150,7 +150,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: ```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -166,7 +166,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: ```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -176,7 +176,7 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: ```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` /// tip diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 156efcc16..7f2e8c157 100644 --- a/docs/em/docs/advanced/response-change-status-code.md +++ b/docs/em/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ & ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 717fb87ce..6b9e9a4d9 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -27,7 +27,7 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index 13ee081c2..dcffc56c6 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ 📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶‍♀️ ⚫️ 📨: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -57,7 +57,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index 27e1cdbd5..cbbbae237 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -7,7 +7,7 @@ & ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚. ```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} +{!../../docs_src/response_headers/tutorial002.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -25,7 +25,7 @@ ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶‍♀️ 🎚 🌖 🔢: ```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} +{!../../docs_src/response_headers/tutorial001.py!} ``` /// note | "📡 ℹ" diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index 33470a726..e6fe3e32c 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -21,7 +21,7 @@ * ⚫️ 🔌 `username` & `password` 📨. ```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} +{!../../docs_src/security/tutorial006.py!} ``` 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -43,7 +43,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. ```Python hl_lines="1 11-21" -{!../../../docs_src/security/tutorial007.py!} +{!../../docs_src/security/tutorial007.py!} ``` 👉 🔜 🎏: @@ -109,5 +109,5 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: ```Python hl_lines="23-27" -{!../../../docs_src/security/tutorial007.py!} +{!../../docs_src/security/tutorial007.py!} ``` diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index 73b2ec540..661be034e 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -63,7 +63,7 @@ Oauth2️⃣ 👫 🎻. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -75,7 +75,7 @@ Oauth2️⃣ 👫 🎻. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: ```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -103,7 +103,7 @@ Oauth2️⃣ 👫 🎻. /// ```Python hl_lines="155" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -131,7 +131,7 @@ Oauth2️⃣ 👫 🎻. /// ```Python hl_lines="4 139 168" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` /// info | "📡 ℹ" @@ -159,7 +159,7 @@ Oauth2️⃣ 👫 🎻. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). ```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ⚙️ `scopes` @@ -175,7 +175,7 @@ Oauth2️⃣ 👫 🎻. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). ```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ✔ `username` & 💽 💠 @@ -193,7 +193,7 @@ Oauth2️⃣ 👫 🎻. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. ```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ✔ `scopes` @@ -203,7 +203,7 @@ Oauth2️⃣ 👫 🎻. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. ```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 🔗 🌲 & ↔ diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index e84941b57..59fb71d73 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -149,7 +149,7 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. ```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` /// tip @@ -167,7 +167,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### 🏃 💽 @@ -203,13 +203,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` & ⤴️ ⚙️ ⚫️ 📁 `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -229,7 +229,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -239,7 +239,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. ```Python hl_lines="5 11-12" -{!../../../docs_src/settings/app02/main.py!} +{!../../docs_src/settings/app02/main.py!} ``` /// tip @@ -253,7 +253,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. ```Python hl_lines="16 18-20" -{!../../../docs_src/settings/app02/main.py!} +{!../../docs_src/settings/app02/main.py!} ``` ### ⚒ & 🔬 @@ -261,7 +261,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -304,7 +304,7 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: ```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} +{!../../docs_src/settings/app03/config.py!} ``` 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. @@ -339,7 +339,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 ```Python hl_lines="1 10" -{!../../../docs_src/settings/app03/main.py!} +{!../../docs_src/settings/app03/main.py!} ``` ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index 1e0931f95..e19f3f234 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 🎧-🈸 @@ -21,7 +21,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 🗻 🎧-🈸 @@ -31,7 +31,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index c45ff47a1..66c7484a6 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -56,7 +56,7 @@ $ pip install jinja2 ⤴️ 👆 💪 ✍ 📄 `templates/item.html` ⏮️: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ⚫️ 🔜 🎦 `id` ✊ ⚪️➡️ "🔑" `dict` 👆 🚶‍♀️: @@ -70,13 +70,13 @@ $ pip install jinja2 & 👆 💪 ⚙️ `url_for()` 🔘 📄, & ⚙️ ⚫️, 🖼, ⏮️ `StaticFiles` 👆 📌. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` 👉 🖼, ⚫️ 🔜 🔗 🎚 📁 `static/styles.css` ⏮️: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` & ↩️ 👆 ⚙️ `StaticFiles`, 👈 🎚 📁 🔜 🍦 🔁 👆 **FastAPI** 🈸 📛 `/static/styles.css`. diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md index 825d545a9..71b29f9b7 100644 --- a/docs/em/docs/advanced/testing-database.md +++ b/docs/em/docs/advanced/testing-database.md @@ -49,7 +49,7 @@ ✋️ 🎂 🎉 📟 🌅 ⚖️ 🌘 🎏, 👥 📁 ⚫️. ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -73,7 +73,7 @@ Base.metadata.create_all(bind=engine) 👥 🚮 👈 ⏸ 📥, ⏮️ 🆕 📁. ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## 🔗 🔐 @@ -81,7 +81,7 @@ Base.metadata.create_all(bind=engine) 🔜 👥 ✍ 🔗 🔐 & 🚮 ⚫️ 🔐 👆 📱. ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -95,7 +95,7 @@ Base.metadata.create_all(bind=engine) ⤴️ 👥 💪 💯 📱 🛎. ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` & 🌐 🛠️ 👥 ⚒ 💽 ⏮️ 💯 🔜 `test.db` 💽 ↩️ 👑 `sql_app.db`. diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 8bcffcc29..027767df1 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -29,7 +29,7 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. ```Python hl_lines="28-29 32" -{!../../../docs_src/dependency_testing/tutorial001.py!} +{!../../docs_src/dependency_testing/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index d64436eb9..071d49c21 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 5fb1e9c34..62939c343 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index edc951d96..ae212364f 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ 👈 👆 💪 🔐 📨 🔗. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 30dc3043e..7957eba1f 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -39,7 +39,7 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## ✍ `websocket` @@ -47,7 +47,7 @@ $ pip install websockets 👆 **FastAPI** 🈸, ✍ `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -63,7 +63,7 @@ $ pip install websockets 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -116,7 +116,7 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: ```Python hl_lines="66-77 76-91" -{!../../../docs_src/websockets/tutorial002.py!} +{!../../docs_src/websockets/tutorial002.py!} ``` /// info @@ -163,7 +163,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. ```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} +{!../../docs_src/websockets/tutorial003.py!} ``` 🔄 ⚫️ 👅: diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 6a4ed073c..8c0008c74 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ & ⤴️ 🗻 👈 🔽 ➡. ```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## ✅ ⚫️ diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a17ba4eec..a5932933a 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ 🖼: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 1f66c6eda..0425e6267 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### ✍ 🛃 `GzipRoute` 🎓 @@ -57,7 +57,7 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -97,13 +97,13 @@ 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## 🛃 `APIRoute` 🎓 📻 @@ -111,11 +111,11 @@ 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index dc9adf80e..698c78ec1 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -47,7 +47,7 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: ```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🏗 🗄 🔗 @@ -55,7 +55,7 @@ ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: ```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🔀 🗄 🔗 @@ -63,7 +63,7 @@ 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: ```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 💾 🗄 🔗 @@ -75,7 +75,7 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. ```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🔐 👩‍🔬 @@ -83,7 +83,7 @@ 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. ```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index b8610b767..5d0d95567 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -36,7 +36,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: ```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} +{!../../docs_src/graphql/tutorial001.py!} ``` 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md index 88b827c24..d25b77894 100644 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ b/docs/em/docs/how-to/sql-databases-peewee.md @@ -71,7 +71,7 @@ ➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽: ```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -131,7 +131,7 @@ connect_args={"check_same_thread": False} 👥 🔜 ✍ `PeeweeConnectionState`: ```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` 👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒. @@ -155,7 +155,7 @@ connect_args={"check_same_thread": False} 🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`: ```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -191,7 +191,7 @@ connect_args={"check_same_thread": False} 🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. ```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` /// tip @@ -225,7 +225,7 @@ connect_args={"check_same_thread": False} ✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰: ```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` /// tip @@ -253,7 +253,7 @@ connect_args={"check_same_thread": False} 👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`: ```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` 📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`. @@ -277,7 +277,7 @@ connect_args={"check_same_thread": False} ✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏: ```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` 📤 🔺 ⏮️ 📟 🇸🇲 🔰. @@ -301,7 +301,7 @@ list(models.User.select()) 📶 🙃 🌌 ✍ 💽 🏓: ```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### ✍ 🔗 @@ -309,7 +309,7 @@ list(models.User.select()) ✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚: ```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` 📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗. @@ -323,7 +323,7 @@ list(models.User.select()) ✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨‍🎨* `dependencies` 🔢: ```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### 🔑 🔢 🎧-🔗 @@ -333,7 +333,7 @@ list(models.User.select()) 👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️). ```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` **⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). @@ -365,7 +365,7 @@ async def reset_db_state(): 🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. ```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### 🔃 `def` 🆚 `async def` @@ -482,31 +482,31 @@ async def reset_db_state(): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` * `sql_app/schemas.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` * `sql_app/main.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ## 📡 ℹ diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index 202c90f94..d2af23bb9 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -23,7 +23,7 @@ ➡️ ▶️ ⏮️ 🙅 🖼: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 🤙 👉 📋 🔢: @@ -39,7 +39,7 @@ John Doe * 🔢 👫 ⏮️ 🚀 🖕. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### ✍ ⚫️ @@ -83,7 +83,7 @@ John Doe 👈 "🆎 🔑": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️: @@ -113,7 +113,7 @@ John Doe ✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` ↩️ 👨‍🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅: @@ -123,7 +123,7 @@ John Doe 🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 📣 🆎 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 💊 🆎 ⏮️ 🆎 🔢 @@ -172,7 +172,7 @@ John Doe ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. @@ -182,7 +182,7 @@ John Doe 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -196,7 +196,7 @@ John Doe 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -234,7 +234,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -242,7 +242,7 @@ John Doe //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -263,7 +263,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -271,7 +271,7 @@ John Doe //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -293,7 +293,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -301,7 +301,7 @@ John Doe //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -315,7 +315,7 @@ John Doe 🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨‍🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁‍♂️. @@ -327,7 +327,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -335,7 +335,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -343,7 +343,7 @@ John Doe //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -364,7 +364,7 @@ John Doe 🖼, ➡️ ✊ 👉 🔢: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` 🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢: @@ -382,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉 👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` & ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶 @@ -446,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉 ➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` ⤴️ 👆 💪 📣 🔢 🆎 `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` & ⤴️, 🔄, 👆 🤚 🌐 👨‍🎨 🐕‍🦺: @@ -476,7 +476,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -484,7 +484,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -492,7 +492,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 1d17a0e4e..0f4585ebe 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -34,7 +34,7 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 🚮 🖥 📋 @@ -42,7 +42,7 @@ 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 📨 ❌: @@ -60,7 +60,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 693a75d28..074ab302c 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ from app.routers import items 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *➡ 🛠️* ⏮️ `APIRouter` @@ -96,7 +96,7 @@ from app.routers import items ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓. @@ -122,7 +122,7 @@ from app.routers import items 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` /// tip @@ -156,7 +156,7 @@ from app.routers import items , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` ➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖: @@ -217,7 +217,7 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### ❔ ⚖ 🗄 👷 @@ -290,7 +290,7 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -318,7 +318,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🗄 `APIRouter` @@ -326,7 +326,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄". @@ -391,7 +391,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🔌 `APIRouter`Ⓜ `users` & `items` @@ -399,7 +399,7 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -441,7 +441,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` ✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`. @@ -449,7 +449,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢. @@ -472,7 +472,7 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index c5a04daeb..eb3093de2 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index c2a9a224d..2e20c83f9 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -48,7 +48,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -56,7 +56,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -103,7 +103,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -111,7 +111,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ q: str | None = None //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -165,7 +165,7 @@ q: str | None = None //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -193,7 +193,7 @@ item: Item = Body(embed=True) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// @@ -201,7 +201,7 @@ item: Item = Body(embed=True) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index 23114540a..3b56b7a07 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -35,7 +35,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 📣 `list` ⏮️ 🆎 🔢 @@ -68,7 +68,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -76,7 +76,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -100,7 +100,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -108,7 +108,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -144,7 +144,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -152,7 +152,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -172,7 +172,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -180,7 +180,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -227,7 +227,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -235,7 +235,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -257,7 +257,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -265,7 +265,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -317,7 +317,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -325,7 +325,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -363,7 +363,7 @@ images: list[Image] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -371,7 +371,7 @@ images: list[Image] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -407,7 +407,7 @@ images: list[Image] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// @@ -415,7 +415,7 @@ images: list[Image] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 97501eb6d..4a4b3b6b8 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -95,7 +95,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -148,7 +148,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -156,7 +156,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -164,7 +164,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 79d8e716f..3468fc512 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 891999028..f4956e76f 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 690b8973a..5829319cb 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index abef2a50c..9320370d6 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 🔃 `__name__ == "__main__"` diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index f14239b0f..3e58d506c 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -86,7 +86,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -112,7 +112,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -122,7 +122,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -130,7 +130,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -152,7 +152,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -160,7 +160,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -206,7 +206,7 @@ commons = Depends(CommonQueryParams) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ commons = Depends(CommonQueryParams) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -254,7 +254,7 @@ commons: CommonQueryParams = Depends() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// @@ -262,7 +262,7 @@ commons: CommonQueryParams = Depends() //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index bf267e056..cd36ad100 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ ⚫️ 🔜 `list` `Depends()`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. @@ -47,7 +47,7 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 🤚 ⚠ @@ -55,7 +55,7 @@ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 📨 💲 @@ -65,7 +65,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 5998d06df..e0d6dba24 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI 🐕‍🦺 🔗 👈 ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -42,7 +42,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -78,7 +78,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -90,7 +90,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -98,7 +98,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 02b33ccd7..a1e7be134 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -21,7 +21,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -37,7 +37,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -45,7 +45,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -64,7 +64,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -72,7 +72,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 314f5b324..21419ef21 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index cbe111079..1d473bd93 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 4703c7123..4fdf196e8 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -171,7 +171,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -179,7 +179,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -201,7 +201,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -209,7 +209,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -237,7 +237,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -245,7 +245,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -261,7 +261,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// @@ -269,7 +269,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index 158189e6e..d8cc05c40 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📁 👈 📁 `main.py`. @@ -134,7 +134,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. @@ -150,7 +150,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 2️⃣: ✍ `FastAPI` "👐" ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -251,7 +251,7 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: @@ -307,7 +307,7 @@ https://example.com/items/foo * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👉 🐍 🔢. @@ -321,7 +321,7 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note @@ -333,7 +333,7 @@ https://example.com/items/foo ### 🔁 5️⃣: 📨 🎚 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index ed32ab53a..7f6a704eb 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### 🗄 `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 🤚 `HTTPException` 👆 📟 @@ -42,7 +42,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 📉 📨 @@ -82,7 +82,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -96,7 +96,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -136,7 +136,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -189,7 +189,7 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "📡 ℹ" @@ -207,7 +207,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` 🔜 🔄 📨 ❌ 🏬 💖: @@ -267,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 82583c7c3..34abd3a4c 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 6caeed4cd..a30db113d 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -18,7 +18,7 @@ 👆 💪 ⚒ 👫 ⏩: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip @@ -52,7 +52,7 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). @@ -68,7 +68,7 @@ ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -98,7 +98,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -117,5 +117,5 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index b9bb12e00..cd0777ebb 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip @@ -60,7 +60,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 1979bed2b..9529928fb 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## 📄 & 📛 @@ -101,7 +101,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -131,7 +131,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-25" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -163,7 +163,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -171,7 +171,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -205,7 +205,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index a7952984c..c25f0323e 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -71,7 +71,7 @@ , 👆 💪 📣 👆 🔢: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## ✔ 🔢 👆 💪, 🎱 @@ -83,7 +83,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -93,7 +93,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -104,7 +104,7 @@ * `le`: `l`👭 🌘 ⚖️ `e`🅾 ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -118,7 +118,7 @@ & 🎏 lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 🌃 diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index e0d51a1df..daf5417eb 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -19,7 +19,7 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 👉 💼, `item_id` 📣 `int`. @@ -122,7 +122,7 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. @@ -130,7 +130,7 @@ ➡, 👆 🚫🔜 ↔ ➡ 🛠️: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -148,7 +148,7 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info @@ -168,7 +168,7 @@ ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ✅ 🩺 @@ -186,7 +186,7 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### 🤚 *🔢 💲* @@ -194,7 +194,7 @@ 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip @@ -210,7 +210,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -251,7 +251,7 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index 23873155e..f75c0a26f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -41,7 +41,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -49,7 +49,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -61,7 +61,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -69,7 +69,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -137,7 +137,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -145,7 +145,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -165,7 +165,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -187,7 +187,7 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note @@ -219,7 +219,7 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` ### ✔ ⏮️ ❕ (`...`) @@ -227,7 +227,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!../../docs_src/query_params_str_validations/tutorial006b.py!} ``` /// info @@ -249,7 +249,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -257,7 +257,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -273,7 +273,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: ```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!../../docs_src/query_params_str_validations/tutorial006d.py!} ``` /// tip @@ -291,7 +291,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -299,7 +299,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -307,7 +307,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -348,7 +348,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -356,7 +356,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -383,7 +383,7 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note @@ -413,7 +413,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -421,7 +421,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -431,7 +431,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -439,7 +439,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -465,7 +465,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -473,7 +473,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -489,7 +489,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -497,7 +497,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -513,7 +513,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// @@ -521,7 +521,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index 9bdab9e3c..c8432f182 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -66,7 +66,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -74,7 +74,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -94,7 +94,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -102,7 +102,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -151,7 +151,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -159,7 +159,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -173,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -221,7 +221,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// @@ -229,7 +229,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 010aa76bf..102690f4b 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -17,7 +17,7 @@ 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## 🔬 `File` 🔢 @@ -25,7 +25,7 @@ ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` /// info @@ -55,7 +55,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -142,7 +142,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -150,7 +150,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 14" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -160,7 +160,7 @@ contents = myfile.file.read() 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: ```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} +{!../../docs_src/request_files/tutorial001_03.py!} ``` ## 💗 📁 📂 @@ -174,7 +174,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -182,7 +182,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -204,7 +204,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// @@ -212,7 +212,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index ab39d1b94..80793dae4 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## 🗄 `File` & `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## 🔬 `File` & `Form` 🔢 @@ -21,7 +21,7 @@ ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index 74117c47d..cbe4e2862 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ 🗄 `Form` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## 🔬 `Form` 🔢 @@ -23,7 +23,7 @@ ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 9483508aa..fb5c17dd6 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -62,7 +62,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -70,7 +70,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -151,7 +151,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -175,7 +175,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -183,7 +183,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -193,7 +193,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -201,7 +201,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -211,7 +211,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -219,7 +219,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -249,7 +249,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -257,7 +257,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -303,7 +303,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -315,7 +315,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -329,7 +329,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -337,7 +337,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} ``` //// @@ -355,7 +355,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -363,7 +363,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -377,7 +377,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -385,7 +385,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -393,7 +393,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -413,7 +413,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -421,7 +421,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -429,7 +429,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -524,7 +524,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -532,7 +532,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -552,7 +552,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// @@ -560,7 +560,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index 57c44777a..cefff708f 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * ♒️. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note @@ -77,7 +77,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 ➡️ 👀 ⏮️ 🖼 🔄: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 👔 📟 "✍". @@ -87,7 +87,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index 8562de09c..e4f877a8e 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-23" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13-21" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20-25" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -91,7 +91,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18-23" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -118,7 +118,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -126,7 +126,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 538ea7b0a..6245f52ab 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -21,7 +21,7 @@ 📁 🖼 📁 `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 🏃 ⚫️ @@ -129,7 +129,7 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip @@ -169,7 +169,7 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 15545f427..4e5b4ebfc 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ✋️ 👈 🚫 👈 ⚠. @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -45,7 +45,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -53,7 +53,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -161,7 +161,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index 3ab8cc986..95fa58f71 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -121,7 +121,7 @@ $ pip install "passlib[bcrypt]" //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -129,7 +129,7 @@ $ pip install "passlib[bcrypt]" //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -171,7 +171,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -179,7 +179,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -195,7 +195,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -203,7 +203,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="88-105" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -217,7 +217,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -225,7 +225,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="114-129" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 937546be8..43d928ce7 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ Oauth2️⃣ 👫 🎻. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -63,7 +63,7 @@ Oauth2️⃣ 👫 🎻. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -125,7 +125,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -165,7 +165,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -213,7 +213,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -221,7 +221,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -253,7 +253,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -261,7 +261,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="55-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 2492c8708..c59d8c131 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -110,13 +110,13 @@ $ pip install sqlalchemy ### 🗄 🇸🇲 🍕 ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ 💽 📛 🇸🇲 ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` 👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). @@ -146,7 +146,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" 👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### 🗒 @@ -184,7 +184,7 @@ connect_args={"check_same_thread": False} ✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ `Base` 🎓 @@ -194,7 +194,7 @@ connect_args={"check_same_thread": False} ⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## ✍ 💽 🏷 @@ -220,7 +220,7 @@ connect_args={"check_same_thread": False} 👫 🎓 🇸🇲 🏷. ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` `__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. @@ -236,7 +236,7 @@ connect_args={"check_same_thread": False} & 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### ✍ 💛 @@ -248,7 +248,7 @@ connect_args={"check_same_thread": False} 👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` 🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. @@ -284,7 +284,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -292,7 +292,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -300,7 +300,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -334,7 +334,7 @@ name: str //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -342,7 +342,7 @@ name: str //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -350,7 +350,7 @@ name: str //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13-15 29-32" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -372,7 +372,7 @@ name: str //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -380,7 +380,7 @@ name: str //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -388,7 +388,7 @@ name: str //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13 17-18 29 34-35" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -466,7 +466,7 @@ current_user.items * ✍ 💗 🏬. ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -487,7 +487,7 @@ current_user.items * `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -539,7 +539,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -547,7 +547,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -577,7 +577,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-20" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -585,7 +585,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="13-18" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -609,7 +609,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24 32 38 47 53" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -617,7 +617,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="22 30 36 45 51" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -637,7 +637,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -645,7 +645,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -732,13 +732,13 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` * `sql_app/schemas.py`: @@ -746,7 +746,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -754,7 +754,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -762,7 +762,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -770,7 +770,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` * `sql_app/main.py`: @@ -778,7 +778,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -786,7 +786,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -843,7 +843,7 @@ $ uvicorn sql_app.main:app --reload //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14-22" -{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} ``` //// @@ -851,7 +851,7 @@ $ uvicorn sql_app.main:app --reload //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="12-20" -{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` //// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 3305746c2..0627031b3 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * "🗻" `StaticFiles()` 👐 🎯 ➡. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "📡 ℹ" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 75dd2d295..5f3d5e736 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -27,7 +27,7 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip @@ -75,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### 🔬 📁 @@ -93,7 +93,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...& ✔️ 📟 💯 💖 ⏭. @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -133,7 +133,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -143,7 +143,7 @@ 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 4fec41213..c038096f9 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note @@ -178,7 +178,7 @@ You can use this same `responses` parameter to add different media types for the For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note @@ -208,7 +208,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd And a response with a status code `200` that uses your `response_model`, but includes a custom `example`: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -244,7 +244,7 @@ You can use that technique to reuse some predefined responses in your *path oper For example: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## More information about OpenAPI responses diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 99ad72b53..6105a301c 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -17,7 +17,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.10+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index f65e1b180..b15a4fe3d 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ To do that, we declare a method `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ To do that, we declare a method `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ And now, we can use `__init__` to declare the parameters of the instance that we //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ And now, we can use `__init__` to declare the parameters of the instance that we //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ We could create an instance of this class with: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ We could create an instance of this class with: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index a528c80fe..232cd6e57 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ For a simple example, let's consider a file structure similar to the one describ The file `main.py` would have: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` The file `test_main.py` would have the tests for `main.py`, it could look like this now: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Run it @@ -61,7 +61,7 @@ $ pytest The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip @@ -73,7 +73,7 @@ Note that the test function is now `async def` instead of just `def` as before w Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` This is the equivalent to: diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index e642b1910..67718a27b 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ In this case, the original path `/app` would actually be served at `/api/v1/app` Even though all your code is written assuming there's just `/app`. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. @@ -99,7 +99,7 @@ You can get the current `root_path` used by your application for each request, i Here we are including it in the message just for demonstration purposes. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Then, if you start Uvicorn with: @@ -128,7 +128,7 @@ The response would be something like: Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. @@ -310,7 +310,7 @@ If you pass a custom list of `servers` and there's a `root_path` (because your A For example: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Will generate an OpenAPI schema like: @@ -359,7 +359,7 @@ The docs UI will interact with the server that you select. If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` and then it won't include it in the OpenAPI schema. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1cefe979f..1d6dc3f6d 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ This is because by default, FastAPI will inspect every item inside and make sure But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning @@ -104,7 +104,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -145,7 +145,7 @@ It accepts the following parameters: FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ Takes some text or bytes and returns an HTML response, as you read above. Takes some text or bytes and returns a plain text response. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -193,7 +193,7 @@ This requires installing `ujson` for example with `pip install ujson`. /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip @@ -209,7 +209,7 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` --- @@ -218,7 +218,7 @@ Or you can use it in the `response_class` parameter: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} +{!../../docs_src/custom_response/tutorial006b.py!} ``` If you do that, then you can return the URL directly from your *path operation* function. @@ -230,7 +230,7 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} +{!../../docs_src/custom_response/tutorial006c.py!} ``` ### `StreamingResponse` @@ -238,7 +238,7 @@ You can also use the `status_code` parameter combined with the `response_class` Takes an async generator or a normal generator/iterator and streams the response body. ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### Using `StreamingResponse` with file-like objects @@ -250,7 +250,7 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. @@ -281,13 +281,13 @@ Takes a different set of arguments to instantiate than the other response types: File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` You can also use the `response_class` parameter: ```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} +{!../../docs_src/custom_response/tutorial009b.py!} ``` In this case, you can return the file path directly from your *path operation* function. @@ -303,7 +303,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: ```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} +{!../../docs_src/custom_response/tutorial009c.py!} ``` Now instead of returning: @@ -331,7 +331,7 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 252ab6fa5..efc07eab2 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -5,7 +5,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use But FastAPI also supports using `dataclasses` the same way: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. @@ -35,7 +35,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us You can also use `dataclasses` in the `response_model` parameter: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` The dataclass will be automatically converted to a Pydantic dataclass. @@ -53,7 +53,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`. In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. We still import `field` from standard `dataclasses`. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 7fd934344..efce492f4 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -31,7 +31,7 @@ Let's start with an example and then see it in detail. We create an async function `lifespan()` with `yield` like this: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. @@ -51,7 +51,7 @@ Maybe you need to start a new version, or you just got tired of running it. 🤷 The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -65,7 +65,7 @@ If you check, the function is decorated with an `@asynccontextmanager`. That converts the function into something called an "**async context manager**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: @@ -89,7 +89,7 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Alternative Events (deprecated) @@ -113,7 +113,7 @@ These functions can be declared with `async def` or normal `def`. To add a function that should be run before the application starts, declare it with the event `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -127,7 +127,7 @@ And your application won't start receiving requests until all the `startup` even To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index faa7c323f..7872103c3 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -35,7 +35,7 @@ Let's start with a simple FastAPI application: //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -43,7 +43,7 @@ Let's start with a simple FastAPI application: //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -154,7 +154,7 @@ For example, you could have a section for **items** and another section for **us //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -162,7 +162,7 @@ For example, you could have a section for **items** and another section for **us //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -215,7 +215,7 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -223,7 +223,7 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -251,7 +251,7 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could ** //// tab | Python ```Python -{!> ../../../docs_src/generate_clients/tutorial004.py!} +{!> ../../docs_src/generate_clients/tutorial004.py!} ``` //// @@ -259,7 +259,7 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could ** //// tab | Node.js ```Javascript -{!> ../../../docs_src/generate_clients/tutorial004.js!} +{!> ../../docs_src/generate_clients/tutorial004.js!} ``` //// diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index ab7778db0..07deac716 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -58,7 +58,7 @@ Enforces that all incoming requests must either be `https` or `wss`. Any incoming request to `http` or `ws` will be redirected to the secure scheme instead. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ Any incoming request to `http` or `ws` will be redirected to the secure scheme i Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` The following arguments are supported: @@ -82,7 +82,7 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc The middleware will handle both standard and streaming responses. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` The following arguments are supported: diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 7fead2ed9..82069a950 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip @@ -93,7 +93,7 @@ Temporarily adopting this point of view (of the *external developer*) can help y First create a new `APIRouter` that will contain one or more callbacks. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Create the callback *path operation* @@ -106,7 +106,7 @@ It should look just like a normal FastAPI *path operation*: * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` There are 2 main differences from a normal *path operation*: @@ -176,7 +176,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index 5ee321e2a..eaaa48a37 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index d599006d2..a61e3f19b 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t You would have to make sure that it is unique for each operation. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Using the *path operation function* name as the operationId @@ -23,7 +23,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ Even if they are in different modules (Python files). To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Advanced description from docstring @@ -57,7 +57,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## Additional Responses @@ -101,7 +101,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -150,7 +150,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: ```Python hl_lines="19-36 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -168,7 +168,7 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v2 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -176,7 +176,7 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v1 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// @@ -196,7 +196,7 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v2 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -204,7 +204,7 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v1 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index b88d74a8a..fc041f7de 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 85e423f42..4467779ba 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -27,7 +27,7 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 092aeceb1..8246b9674 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ For example, you cannot put a Pydantic model in a `JSONResponse` without first c For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Technical Details" @@ -57,7 +57,7 @@ Let's say that you want to return an ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Then, when you type that username and password, the browser sends them in the he //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Then we can use `secrets.compare_digest()` to ensure that `credentials.username` //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Then we can use `secrets.compare_digest()` to ensure that `credentials.username` //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ After detecting that the credentials are incorrect, return an `HTTPException` wi //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ After detecting that the credentials are incorrect, return an `HTTPException` wi //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index fdd8db7b9..3db284d02 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.10+ ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.9+ ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.8+ ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.10+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.9+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.8+ ```Python hl_lines="64-67" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.10+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.9+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.8+ ```Python hl_lines="157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.10+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.9+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.8+ ```Python hl_lines="5 141 172" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.10+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.9+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.8+ ```Python hl_lines="9 107" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.10+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.9+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.8+ ```Python hl_lines="107 109-117" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.10+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.9+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.8+ ```Python hl_lines="48 118-129" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.10+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.9+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.8+ ```Python hl_lines="130-136" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 8c04d2507..01810c438 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -63,7 +63,7 @@ You can use all the same validation features and tools you use for Pydantic mode //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -97,7 +97,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Run the server @@ -133,13 +133,13 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` And then use it in a file `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -159,7 +159,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Notice that now we don't create a default instance `settings = Settings()`. @@ -171,7 +171,7 @@ Now we create a dependency that returns a new `config.Settings()`. //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -179,7 +179,7 @@ Now we create a dependency that returns a new `config.Settings()`. //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -211,7 +211,7 @@ And then we can require it from the *path operation function* as a dependency an //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -219,7 +219,7 @@ And then we can require it from the *path operation function* as a dependency an //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -233,7 +233,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -243,7 +243,7 @@ Prefer to use the `Annotated` version if possible. Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -288,7 +288,7 @@ And then update your `config.py` with: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// tip @@ -302,7 +302,7 @@ The `model_config` attribute is used just for Pydantic configuration. You can re //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// tip @@ -347,7 +347,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -355,7 +355,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -369,7 +369,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index 568a9deca..befa9908a 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Sub-application @@ -21,7 +21,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Mount the sub-application @@ -31,7 +31,7 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Check the automatic API docs diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 416540ba4..d688c5cb7 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -58,7 +58,7 @@ You could also use `from starlette.templating import Jinja2Templates`. Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template Context Values @@ -112,13 +112,13 @@ For example, with an ID of `42`, this would render: You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In this example, it would link to a CSS file at `static/styles.css` with: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md index 974cf4caa..2b704f229 100644 --- a/docs/en/docs/advanced/testing-database.md +++ b/docs/en/docs/advanced/testing-database.md @@ -59,7 +59,7 @@ We'll use an in-memory database that persists during the tests instead of the lo But the rest of the session code is more or less the same, we just copy it. ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -83,7 +83,7 @@ That is normally called in `main.py`, but the line in `main.py` uses the databas So we add that line here, with the new file. ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## Dependency override @@ -91,7 +91,7 @@ So we add that line here, with the new file. Now we create the dependency override and add it to the overrides for our app. ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -105,7 +105,7 @@ The code for `override_get_db()` is almost exactly the same as for `get_db()`, b Then we can just test the app as normally. ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 92e25f88d..1cc4313a1 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index b24a2ccfe..f48907c7c 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 6c071bc19..ab08c90fe 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 5473db5cb..917d77a95 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 44c6c7428..8947f32e7 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -39,7 +39,7 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## Create a `websocket` @@ -47,7 +47,7 @@ But it's the simplest way to focus on the server-side of WebSockets and have a w In your **FastAPI** application, create a `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "Technical Details" @@ -63,7 +63,7 @@ You could also use `from starlette.websockets import WebSocket`. In your WebSocket route you can `await` for messages and send messages. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` You can receive and send binary, text, and JSON data. @@ -118,7 +118,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -126,7 +126,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -134,7 +134,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -148,7 +148,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -213,7 +213,7 @@ When a WebSocket connection is closed, the `await websocket.receive_text()` will //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -221,7 +221,7 @@ When a WebSocket connection is closed, the `await websocket.receive_text()` will //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index f07609ed6..3974d491c 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Check it diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index a75f8ef58..a72316c4d 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -43,7 +43,7 @@ This section doesn't apply those ideas, to be equivalent to the counterpart in < * Create a table `notes` using the `metadata` object. ```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// tip @@ -61,7 +61,7 @@ Notice that all this code is pure SQLAlchemy Core. * Create a `database` object. ```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// tip @@ -80,7 +80,7 @@ Here, this section would run directly, right before starting your **FastAPI** ap * Create all the tables from the `metadata` object. ```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Create models @@ -91,7 +91,7 @@ Create Pydantic models for: * Notes to be returned (`Note`). ```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). @@ -104,7 +104,7 @@ So, you will be able to see it all in the interactive API docs. * Create event handlers to connect and disconnect from the database. ```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Read notes @@ -112,7 +112,7 @@ So, you will be able to see it all in the interactive API docs. Create the *path operation function* to read notes: ```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// note @@ -132,7 +132,7 @@ That documents (and validates, serializes, filters) the output data, as a `list` Create the *path operation function* to create notes: ```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// info diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index add16fbec..6cd0385a2 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP For example: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index 040c3926b..2c649c152 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Without changing the settings, syntax highlighting is enabled by default: But you can disable it by setting `syntaxHighlight` to `False`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...and then Swagger UI won't show the syntax highlighting anymore: @@ -31,7 +31,7 @@ But you can disable it by setting `syntaxHighlight` to `False`: The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` That configuration would change the syntax highlighting color theme: @@ -45,7 +45,7 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` You can override any of them by setting a different value in the argument `swagger_ui_parameters`. @@ -53,7 +53,7 @@ You can override any of them by setting a different value in the argument `swagg For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Other Swagger UI Parameters diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 0c766d3e4..16c873d11 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -19,7 +19,7 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: ```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Include the custom docs @@ -37,7 +37,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs And similarly for ReDoc... ```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` /// tip @@ -55,7 +55,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: ```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Test it @@ -125,7 +125,7 @@ After that, your file structure could look like: * "Mount" a `StaticFiles()` instance in a specific path. ```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Test the static files @@ -159,7 +159,7 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: ```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Include the custom docs for static files @@ -177,7 +177,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t And similarly for ReDoc... ```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` /// tip @@ -195,7 +195,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: ```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Test Static Files UI diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index 20e1904f1..a62ebf1d5 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Create a custom `GzipRoute` class @@ -57,7 +57,7 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "Technical Details" @@ -97,13 +97,13 @@ We can also use this same approach to access the request body in an exception ha All we need to do is handle the request inside a `try`/`except` block: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Custom `APIRoute` class in a router @@ -111,11 +111,11 @@ If an exception occurs, the`Request` instance will still be in scope, so we can You can also set the `route_class` parameter of an `APIRouter`: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index 9909f778c..2b0367952 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -44,7 +44,7 @@ For example, let's add Strawberry documentation. diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index a0abfe21d..feb4025dd 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -39,7 +39,7 @@ There is an official project generator with **FastAPI** and **Couchbase**, all b For now, don't pay attention to the rest, only the imports: ```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Define a constant to use as a "document type" @@ -49,7 +49,7 @@ We will use it later as a fixed field `type` in our documents. This is not required by Couchbase, but is a good practice that will help you afterwards. ```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Add a function to get a `Bucket` @@ -74,7 +74,7 @@ This utility function will: * Return it. ```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Create Pydantic models @@ -86,7 +86,7 @@ As **Couchbase** "documents" are actually just "JSON objects", we can model them First, let's create a `User` model: ```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. @@ -100,7 +100,7 @@ This will have the data that is actually stored in the database. We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: ```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` /// note @@ -123,7 +123,7 @@ Now create a function that will: By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add unit tests for it: ```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ### f-strings @@ -158,7 +158,7 @@ UserInDB(username="johndoe", hashed_password="some_hash") ### Create the `FastAPI` app ```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ### Create the *path operation function* @@ -168,7 +168,7 @@ As our code is calling Couchbase and we are not using the threads", so, we can just get the bucket directly and pass it to our utility functions: ```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Recap diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 0ab5b1337..75fd3f9b6 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -13,7 +13,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} # Code below omitted 👇 ``` @@ -22,7 +22,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ```
@@ -32,7 +32,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} # Code below omitted 👇 ``` @@ -41,7 +41,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -51,7 +51,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} # Code below omitted 👇 ``` @@ -60,7 +60,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -74,7 +74,7 @@ If you use this model as an input like here: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} # Code below omitted 👇 ``` @@ -83,7 +83,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` @@ -93,7 +93,7 @@ If you use this model as an input like here: //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} # Code below omitted 👇 ``` @@ -102,7 +102,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -112,7 +112,7 @@ If you use this model as an input like here: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} # Code below omitted 👇 ``` @@ -121,7 +121,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -145,7 +145,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` //// @@ -153,7 +153,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` //// @@ -161,7 +161,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` //// @@ -226,7 +226,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} ``` //// @@ -234,7 +234,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} ``` //// @@ -242,7 +242,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} ``` //// diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md index e411c200c..e73ca369b 100644 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -89,7 +89,7 @@ Let's refer to the file `sql_app/database.py`. Let's first check all the normal Peewee code, create a Peewee database: ```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -149,7 +149,7 @@ This might seem a bit complex (and it actually is), you don't really need to com We will create a `PeeweeConnectionState`: ```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` This class inherits from a special internal class used by Peewee. @@ -173,7 +173,7 @@ But it doesn't give Peewee async super-powers. You should still use normal `def` Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: ```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -209,7 +209,7 @@ But Pydantic also uses the term "**model**" to refer to something different, the Import `db` from `database` (the file `database.py` from above) and use it here. ```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` /// tip @@ -243,7 +243,7 @@ So this will help us avoiding confusion while using both. Create all the same Pydantic models as in the SQLAlchemy tutorial: ```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` /// tip @@ -271,7 +271,7 @@ But recent versions of Pydantic allow providing a custom class that inherits fro We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: ```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. @@ -295,7 +295,7 @@ Now let's see the file `sql_app/crud.py`. Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: ```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` There are some differences with the code for the SQLAlchemy tutorial. @@ -319,7 +319,7 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part In a very simplistic way create the database tables: ```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Create a dependency @@ -327,7 +327,7 @@ In a very simplistic way create the database tables: Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: ```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` Here we have an empty `yield` because we are actually not using the database object directly. @@ -341,7 +341,7 @@ And then, in each *path operation function* that needs to access the database we But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: ```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Context variable sub-dependency @@ -351,7 +351,7 @@ For all the `contextvars` parts to work, we need to make sure we have an indepen For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). ```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). @@ -383,7 +383,7 @@ async def reset_db_state(): Now, finally, here's the standard **FastAPI** *path operations* code. ```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### About `def` vs `async def` @@ -500,31 +500,31 @@ Repeat the same process with the 10 tabs. This time all of them will wait and yo * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` * `sql_app/schemas.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` * `sql_app/main.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ## Technical Details diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 6994adb5f..ee192d8cb 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -23,7 +23,7 @@ If you are a Python expert, and you already know everything about type hints, sk Let's start with a simple example: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Calling this program outputs: @@ -39,7 +39,7 @@ The function does the following: * Concatenates them with a space in the middle. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edit it @@ -83,7 +83,7 @@ That's it. Those are the "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` That is not the same as declaring default values like would be with: @@ -113,7 +113,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring Check this function, it already has type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Because the editor knows the types of the variables, you don't only get completion, you also get error checks: @@ -123,7 +123,7 @@ Because the editor knows the types of the variables, you don't only get completi Now you know that you have to fix it, convert `age` to a string with `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Declaring types @@ -144,7 +144,7 @@ You can use, for example: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic types with type parameters @@ -182,7 +182,7 @@ As the type, put `list`. As the list is a type that contains some internal types, you put them in square brackets: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ As the list is a type that contains some internal types, you put them in square From `typing`, import `List` (with a capital `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Declare the variable, with the same colon (`:`) syntax. @@ -202,7 +202,7 @@ As the type, put the `List` that you imported from `typing`. As the list is a type that contains some internal types, you put them in square brackets: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ You would do the same to declare `tuple`s and `set`s: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ You would do the same to declare `tuple`s and `set`s: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ The second type parameter is for the values of the `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ The second type parameter is for the values of the `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ You can declare that a value could have a type, like `str`, but that it could al In Python 3.6 and above (including Python 3.10) you can declare it by importing and using `Optional` from the `typing` module. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. @@ -333,7 +333,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ It's just about the words and names. But those words can affect how you and your As an example, let's take this function: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter: @@ -388,7 +388,7 @@ say_hi(name=None) # This works, None is valid 🎉 The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` And then you won't have to worry about names like `Optional` and `Union`. 😎 @@ -452,13 +452,13 @@ You can also declare a class as the type of a variable. Let's say you have a class `Person`, with a name: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Then you can declare a variable to be of type `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` And then, again, you get all the editor support: @@ -486,7 +486,7 @@ An example from the official Pydantic docs: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ An example from the official Pydantic docs: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ An example from the official Pydantic docs: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python also has a feature that allows putting **additional ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ In versions below Python 3.9, you import `Annotated` from `typing_extensions`. It will already be installed with **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 8b4476e41..1cd460b07 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ This includes, for example: First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter. @@ -34,7 +34,7 @@ In this case, the task function will write to a file (simulating sending an emai And as the write operation doesn't use `async` and `await`, we define the function with normal `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Add the background task @@ -42,7 +42,7 @@ And as the write operation doesn't use `async` and `await`, we define the functi Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` receives as arguments: @@ -60,7 +60,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.10+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.9+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.8+ ```Python hl_lines="14 16 23 26" -{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 1c33fd051..4ec9b15bd 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ You can create the *path operations* for that module using `APIRouter`. You import it and create an "instance" the same way you would with the class `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Path operations* with `APIRouter` @@ -96,7 +96,7 @@ And then you use it to declare your *path operations*. Use it the same way you would use the `FastAPI` class: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` You can think of `APIRouter` as a "mini `FastAPI`" class. @@ -124,7 +124,7 @@ We will now use a simple dependency to read a custom `X-Token` header: //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ We will now use a simple dependency to read a custom `X-Token` header: //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ We know all the *path operations* in this module have the same: So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` As the path of each *path operation* has to start with `/`, like in: @@ -243,7 +243,7 @@ And we need to get the dependency function from the module `app.dependencies`, t So we use a relative import with `..` for the dependencies: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### How relative imports work @@ -316,7 +316,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -344,7 +344,7 @@ You import and create a `FastAPI` class as normally. And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Import the `APIRouter` @@ -352,7 +352,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` As the files `app/routers/users.py` and `app/routers/items.py` are submodules that are part of the same Python package `app`, we can use a single dot `.` to import them using "relative imports". @@ -417,7 +417,7 @@ the `router` from `users` would overwrite the one from `items` and we wouldn't b So, to be able to use both of them in the same file, we import the submodules directly: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Include the `APIRouter`s for `users` and `items` @@ -425,7 +425,7 @@ So, to be able to use both of them in the same file, we import the submodules di Now, let's include the `router`s from the submodules `users` and `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -467,7 +467,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` But we still want to set a custom `prefix` when including the `APIRouter` so that all its *path operations* start with `/admin`, we want to secure it with the `dependencies` we already have for this project, and we want to include `tags` and `responses`. @@ -475,7 +475,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. @@ -498,7 +498,7 @@ We can also add *path operations* directly to the `FastAPI` app. Here we do it... just to show that we can 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` and it will work correctly, together with all the other *path operations* added with `app.include_router()`. diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 466df29f1..30a5c623f 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ First, you have to import it: //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First, you have to import it: //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First, you have to import it: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index d63cd2529..eebbb3fe4 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ For example: //// tab | Python 3.10+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ For example: //// tab | Python 3.9+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ For example: //// tab | Python 3.8+ ```Python hl_lines="29" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ as in: //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ as in: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ as in: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index d2bda5979..38f3eb136 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ You can define an attribute to be a subtype. For example, a Python `list`: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ You can define an attribute to be a subtype. For example, a Python `list`: //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ In Python 3.9 and above you can use the standard `list` to declare these type an But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Declare a `list` with a type parameter @@ -68,7 +68,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ For example, we can define an `Image` model: //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ For example, we can define an `Image` model: //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ For example, we can define an `Image` model: //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ as in: //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ as in: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3257f9a08..3ac2e3914 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.8+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -87,7 +87,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -95,7 +95,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -103,7 +103,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.8+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -125,7 +125,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -133,7 +133,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -141,7 +141,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.8+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -164,7 +164,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -180,7 +180,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.8+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 83f08ce84..14d621418 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -25,7 +25,7 @@ First, you need to import `BaseModel` from `pydantic`: //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ First, you need to import `BaseModel` from `pydantic`: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ Use standard Python types for all the attributes: //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Use standard Python types for all the attributes: //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ To add it to your *path operation*, declare it the same way you declared path an //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ To add it to your *path operation*, declare it the same way you declared path an //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Inside of the function, you can access all the attributes of the model object di //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Inside of the function, you can access all the attributes of the model object di //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ You can declare path parameters and request body at the same time. //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ You can declare path parameters and request body at the same time. //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ You can also declare **body**, **path** and **query** parameters, all at the sam //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ You can also declare **body**, **path** and **query** parameters, all at the sam //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md index 2aa3a1f59..62cafbb23 100644 --- a/docs/en/docs/tutorial/cookie-param-models.md +++ b/docs/en/docs/tutorial/cookie-param-models.md @@ -23,7 +23,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.10+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} ``` //// @@ -31,7 +31,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.9+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} ``` //// @@ -39,7 +39,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.8+ ```Python hl_lines="10-13 17" -{!> ../../../docs_src/cookie_param_models/tutorial001_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-10 14" -{!> ../../../docs_src/cookie_param_models/tutorial001_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} ``` //// @@ -67,7 +67,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001.py!} +{!> ../../docs_src/cookie_param_models/tutorial001.py!} ``` //// @@ -103,7 +103,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} ``` //// @@ -111,7 +111,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/cookie_param_models/tutorial002_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} ``` //// @@ -125,7 +125,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002.py!} +{!> ../../docs_src/cookie_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 0214a9c38..8804f854f 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ First import `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First import `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First import `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 7dd0a5df5..8dfc9bad9 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -47,7 +47,7 @@ You can also specify whether your backend allows: * Specific HTTP headers or all of them with the wildcard `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context. diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index c520a631d..6c0177853 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code In your FastAPI application, import and run `uvicorn` directly: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### About `__name__ == "__main__"` diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index b3394f14e..defd61a0d 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ The same example would then look like: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ The same example would then look like: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ The same example would then look like: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 7c3ac7922..e89d520be 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ It should be a `list` of `Depends()`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ It should be a `list` of `Depends()`: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ They can declare request requirements (like headers) or other sub-dependencies: //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ They can declare request requirements (like headers) or other sub-dependencies: //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ So, you can reuse a normal dependency (that returns a value) you already use som //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ So, you can reuse a normal dependency (that returns a value) you already use som //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 2a3ac2237..97da668aa 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ For example, you could use this to create a database session and close it after Only the code prior to and including the `yield` statement is executed before creating a response: ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` The yielded value is what is injected into *path operations* and other dependencies: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` The code following the `yield` statement is executed after the response has been delivered: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip @@ -64,7 +64,7 @@ So, you can look for that specific exception inside the dependency with `except In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Sub-dependencies with `yield` @@ -78,7 +78,7 @@ For example, `dependency_c` can have a dependency on `dependency_b`, and `depend //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ For example, `dependency_c` can have a dependency on `dependency_b`, and `depend //// tab | Python 3.8+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de //// tab | Python 3.8+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ But it's there for you if you need it. 🤓 //// tab | Python 3.9+ ```Python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ But it's there for you if you need it. 🤓 //// tab | Python 3.8+ ```Python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -210,7 +210,7 @@ If you catch an exception using `except` in a dependency with `yield` and you do //// tab | Python 3.9+ ```Python hl_lines="15-16" -{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -218,7 +218,7 @@ If you catch an exception using `except` in a dependency with `yield` and you do //// tab | Python 3.8+ ```Python hl_lines="14-15" -{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +{!> ../../docs_src/dependencies/tutorial008c_an.py!} ``` //// @@ -232,7 +232,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13-14" -{!> ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -248,7 +248,7 @@ You can re-raise the same exception using `raise`: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} ``` //// @@ -256,7 +256,7 @@ You can re-raise the same exception using `raise`: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -270,7 +270,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial008d.py!} +{!> ../../docs_src/dependencies/tutorial008d.py!} ``` //// @@ -404,7 +404,7 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using `with` or `async with` statements inside of the dependency function: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` /// tip diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 03a9a42f0..21a8cb6be 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ In that case, they will be applied to all the *path operations* in the applicati //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ In that case, they will be applied to all the *path operations* in the applicati //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index a608222f2..b50edb98e 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 85b252e13..2b098d159 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Then we can use the dependency with: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Then we can use the dependency with: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Then we can use the dependency with: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md index c110a2ac5..039ac6714 100644 --- a/docs/en/docs/tutorial/encoder.md +++ b/docs/en/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ It receives an object, like a Pydantic model, and returns a JSON compatible vers //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ It receives an object, like a Pydantic model, and returns a JSON compatible vers //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 3009acaf3..65f9f1085 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 1c87e76ce..4e6f69f31 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Here's a general idea of how the models could look like with their password fiel //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Here's a general idea of how the models could look like with their password fiel //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -179,7 +179,7 @@ That way, we can declare just the differences between the models (with plaintext //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -187,7 +187,7 @@ That way, we can declare just the differences between the models (with plaintext //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -209,7 +209,7 @@ When defining a ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -217,7 +217,7 @@ When defining a ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -245,7 +245,7 @@ For that, use the standard Python `typing.List` (or just `list` in Python 3.9 an //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -253,7 +253,7 @@ For that, use the standard Python `typing.List` (or just `list` in Python 3.9 an //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -269,7 +269,7 @@ In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above) //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -277,7 +277,7 @@ In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above) //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index b48a0ee38..77728cebe 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ The simplest FastAPI file could look like this: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copy that to a file `main.py`. @@ -158,7 +158,7 @@ You could also use it to generate code automatically, for clients that communica ### Step 1: import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` is a Python class that provides all the functionality for your API. @@ -174,7 +174,7 @@ You can use all the ../../../docs_src/header_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Declare the **header parameters** that you need in a **Pydantic model**, and the //// tab | Python 3.9+ ```Python hl_lines="9-14 18" -{!> ../../../docs_src/header_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Declare the **header parameters** that you need in a **Pydantic model**, and the //// tab | Python 3.8+ ```Python hl_lines="10-15 19" -{!> ../../../docs_src/header_param_models/tutorial001_an.py!} +{!> ../../docs_src/header_param_models/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-12 16" -{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-14 18" -{!> ../../../docs_src/header_param_models/tutorial001_py39.py!} +{!> ../../docs_src/header_param_models/tutorial001_py39.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-12 16" -{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} ``` //// @@ -99,7 +99,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_an_py310.py!} +{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} ``` //// @@ -107,7 +107,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} ``` //// @@ -115,7 +115,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/header_param_models/tutorial002_an.py!} +{!> ../../docs_src/header_param_models/tutorial002_an.py!} ``` //// @@ -129,7 +129,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_param_models/tutorial002_py310.py!} +{!> ../../docs_src/header_param_models/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_py39.py!} +{!> ../../docs_src/header_param_models/tutorial002_py39.py!} ``` //// @@ -157,7 +157,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002.py!} +{!> ../../docs_src/header_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index 2e07fe0e6..293de897f 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ First import `Header`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First import `Header`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First import `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index c62509b8b..715bb999a 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -19,7 +19,7 @@ You can set the following fields that are used in the OpenAPI specification and You can set them as follows: ```Python hl_lines="3-16 19-32" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip @@ -39,7 +39,7 @@ Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with For example: ```Python hl_lines="31" -{!../../../docs_src/metadata/tutorial001_1.py!} +{!../../docs_src/metadata/tutorial001_1.py!} ``` ## Metadata for tags @@ -63,7 +63,7 @@ Let's try that in an example with tags for `users` and `items`. Create metadata for your tags and pass it to the `openapi_tags` parameter: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). @@ -79,7 +79,7 @@ You don't have to add metadata for all the tags that you use. Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -109,7 +109,7 @@ But you can configure it with the parameter `openapi_url`. For example, to set it to be served at `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it. @@ -128,5 +128,5 @@ You can configure the two documentation user interfaces included: For example, to set Swagger UI to be served at `/documentation` and disable ReDoc: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 199b593d3..7c4954c7b 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ The middleware function receives: * You can then further modify the `response` before returning it. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip @@ -60,7 +60,7 @@ And also after the `response` is generated, before returning it. For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index a1a4953a6..4ca6ebf13 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ In these cases, it could make sense to store the tags in an `Enum`. **FastAPI** supports that the same way as with plain strings: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Summary and description @@ -101,7 +101,7 @@ You can add a `summary` and `description`: //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ You can add a `summary` and `description`: //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ You can add a `summary` and `description`: //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ So, if you don't provide one, **FastAPI** will automatically generate one of "Su If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` It will be clearly marked as deprecated in the interactive docs: diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index bd835d0d4..9ddf49ea9 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -173,7 +173,7 @@ But keep in mind that if you use `Annotated`, you won't have this problem, it wo //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -181,7 +181,7 @@ But keep in mind that if you use `Annotated`, you won't have this problem, it wo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -210,7 +210,7 @@ Pass `*`, as the first parameter of the function. Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Better with `Annotated` @@ -220,7 +220,7 @@ Keep in mind that if you use `Annotated`, as you are not using function paramete //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -228,7 +228,7 @@ Keep in mind that if you use `Annotated`, as you are not using function paramete //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -242,7 +242,7 @@ Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than o //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -250,7 +250,7 @@ Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than o //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -264,7 +264,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -279,7 +279,7 @@ The same applies for: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -287,7 +287,7 @@ The same applies for: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -301,7 +301,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ And the same for lt. //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -327,7 +327,7 @@ And the same for lt. //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -341,7 +341,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index a87a29e08..fd9e74585 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ You can declare path "parameters" or "variables" with the same syntax used by Python format strings: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` The value of the path parameter `item_id` will be passed to your function as the argument `item_id`. @@ -19,7 +19,7 @@ So, if you run this example and go to ../../../docs_src/query_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Declare the **query parameters** that you need in a **Pydantic model**, and then //// tab | Python 3.9+ ```Python hl_lines="8-12 16" -{!> ../../../docs_src/query_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Declare the **query parameters** that you need in a **Pydantic model**, and then //// tab | Python 3.8+ ```Python hl_lines="10-14 18" -{!> ../../../docs_src/query_param_models/tutorial001_an.py!} +{!> ../../docs_src/query_param_models/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13 17" -{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-12 16" -{!> ../../../docs_src/query_param_models/tutorial001_py39.py!} +{!> ../../docs_src/query_param_models/tutorial001_py39.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13 17" -{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} ``` //// @@ -99,7 +99,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_param_models/tutorial002_an_py310.py!} +{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} ``` //// @@ -107,7 +107,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} ``` //// @@ -115,7 +115,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_param_models/tutorial002_an.py!} +{!> ../../docs_src/query_param_models/tutorial002_an.py!} ``` //// @@ -129,7 +129,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_param_models/tutorial002_py310.py!} +{!> ../../docs_src/query_param_models/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_param_models/tutorial002_py39.py!} +{!> ../../docs_src/query_param_models/tutorial002_py39.py!} ``` //// @@ -157,7 +157,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_param_models/tutorial002.py!} +{!> ../../docs_src/query_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index dd101a2a6..12778d7fe 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ Let's take this application as example: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ Let's take this application as example: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ To achieve that, first import: In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ In versions of Python below Python 3.9 you import `Annotated` from `typing_exten It will already be installed with FastAPI. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -126,7 +126,7 @@ Now that we have this `Annotated` where we can put more information (in this cas //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -134,7 +134,7 @@ Now that we have this `Annotated` where we can put more information (in this cas //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -170,7 +170,7 @@ This is how you would use `Query()` as the default value of your function parame //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ This is how you would use `Query()` as the default value of your function parame //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -284,7 +284,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -292,7 +292,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -300,7 +300,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -314,7 +314,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -328,7 +328,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -340,7 +340,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -348,7 +348,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -356,7 +356,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -370,7 +370,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -384,7 +384,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -408,7 +408,7 @@ You could still see some code using it: //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} ``` //// @@ -424,7 +424,7 @@ Let's say that you want to declare the `q` query parameter to have a `min_length //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -432,7 +432,7 @@ Let's say that you want to declare the `q` query parameter to have a `min_length //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -446,7 +446,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -494,7 +494,7 @@ So, when you need to declare a value as required while using `Query`, you can si //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -502,7 +502,7 @@ So, when you need to declare a value as required while using `Query`, you can si //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -516,7 +516,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip @@ -536,7 +536,7 @@ There's an alternative way to explicitly declare that a value is required. You c //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -544,7 +544,7 @@ There's an alternative way to explicitly declare that a value is required. You c //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -558,7 +558,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -582,7 +582,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -590,7 +590,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -598,7 +598,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -612,7 +612,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -626,7 +626,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -652,7 +652,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -660,7 +660,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -668,7 +668,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -682,7 +682,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -696,7 +696,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -710,7 +710,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -751,7 +751,7 @@ And you can also define a default `list` of values if none are provided: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -759,7 +759,7 @@ And you can also define a default `list` of values if none are provided: //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -773,7 +773,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -787,7 +787,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -816,7 +816,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -824,7 +824,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -838,7 +838,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -870,7 +870,7 @@ You can add a `title`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -878,7 +878,7 @@ You can add a `title`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -886,7 +886,7 @@ You can add a `title`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -900,7 +900,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -914,7 +914,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -924,7 +924,7 @@ And a `description`: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -932,7 +932,7 @@ And a `description`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -940,7 +940,7 @@ And a `description`: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -954,7 +954,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -968,7 +968,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -994,7 +994,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -1002,7 +1002,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1010,7 +1010,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1024,7 +1024,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1038,7 +1038,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1054,7 +1054,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1062,7 +1062,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1070,7 +1070,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1084,7 +1084,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1098,7 +1098,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1114,7 +1114,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1122,7 +1122,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1130,7 +1130,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1144,7 +1144,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1158,7 +1158,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index a98ac9b28..0d31d453d 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters. @@ -66,7 +66,7 @@ The same way, you can declare optional query parameters, by setting their defaul //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ The same way, you can declare optional query parameters, by setting their defaul //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ You can also declare `bool` types, and they will be converted: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ You can also declare `bool` types, and they will be converted: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ They will be detected by name: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ They will be detected by name: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ If you don't want to add a specific value but just make it optional, set the def But when you want to make a query parameter required, you can just not declare any default value: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Here the query parameter `needy` is a required query parameter of type `str`. @@ -223,7 +223,7 @@ And of course, you can define some parameters as required, some as having a defa //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -231,7 +231,7 @@ And of course, you can define some parameters as required, some as having a defa //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 9f19596a8..f3f1eb103 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -23,7 +23,7 @@ Import `File` and `UploadFile` from `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Import `File` and `UploadFile` from `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ Create file parameters the same way you would for `Body` or `Form`: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ Create file parameters the same way you would for `Body` or `Form`: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -113,7 +113,7 @@ Define a file parameter with a type of `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -121,7 +121,7 @@ Define a file parameter with a type of `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -135,7 +135,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -224,7 +224,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -232,7 +232,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -240,7 +240,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -254,7 +254,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -268,7 +268,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -280,7 +280,7 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -288,7 +288,7 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -302,7 +302,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -318,7 +318,7 @@ To use that, declare a list of `bytes` or `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -326,7 +326,7 @@ To use that, declare a list of `bytes` or `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -340,7 +340,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -354,7 +354,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -376,7 +376,7 @@ And the same way as before, you can use `File()` to set additional parameters, e //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -384,7 +384,7 @@ And the same way as before, you can use `File()` to set additional parameters, e //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -398,7 +398,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -412,7 +412,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index 1440d17b8..f1142877a 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -27,7 +27,7 @@ You just need to declare a **Pydantic model** with the fields you want to receiv //// tab | Python 3.9+ ```Python hl_lines="9-11 15" -{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} ``` //// @@ -35,7 +35,7 @@ You just need to declare a **Pydantic model** with the fields you want to receiv //// tab | Python 3.8+ ```Python hl_lines="8-10 14" -{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +{!> ../../docs_src/request_form_models/tutorial001_an.py!} ``` //// @@ -49,7 +49,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-9 13" -{!> ../../../docs_src/request_form_models/tutorial001.py!} +{!> ../../docs_src/request_form_models/tutorial001.py!} ``` //// @@ -79,7 +79,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +{!> ../../docs_src/request_form_models/tutorial002_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/request_form_models/tutorial002.py!} +{!> ../../docs_src/request_form_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 7830a2ba4..d60fc4c00 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -19,7 +19,7 @@ $ pip install python-multipart //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ $ pip install python-multipart //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Create file and form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Create file and form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 87cfdefbc..2ccc6886e 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -21,7 +21,7 @@ Import `Form` from `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Import `Form` from `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ Create form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -63,7 +63,7 @@ Create form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -77,7 +77,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 6a2093e6d..36ccfc4ce 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -152,7 +152,7 @@ And we are using this model to declare our input and the same model to declare o //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -160,7 +160,7 @@ And we are using this model to declare our input and the same model to declare o //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -184,7 +184,7 @@ We can instead create an input model with the plaintext password and an output m //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -192,7 +192,7 @@ We can instead create an input model with the plaintext password and an output m //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -202,7 +202,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -210,7 +210,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -220,7 +220,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -228,7 +228,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -258,7 +258,7 @@ And in those cases, we can use classes and inheritance to take advantage of func //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -266,7 +266,7 @@ And in those cases, we can use classes and inheritance to take advantage of func //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -312,7 +312,7 @@ There might be cases where you return something that is not a valid Pydantic fie The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. @@ -324,7 +324,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse` You can also use a subclass of `Response` in the type annotation: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case. @@ -338,7 +338,7 @@ The same would happen if you had something like a ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -364,7 +364,7 @@ In this case, you can disable the response model generation by setting `response //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -372,7 +372,7 @@ In this case, you can disable the response model generation by setting `response //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -386,7 +386,7 @@ Your response model could have default values, like: //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -394,7 +394,7 @@ Your response model could have default values, like: //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -402,7 +402,7 @@ Your response model could have default values, like: //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -422,7 +422,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -430,7 +430,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -438,7 +438,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -541,7 +541,7 @@ This also applies to `response_model_by_alias` that works similarly. //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -549,7 +549,7 @@ This also applies to `response_model_by_alias` that works similarly. //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -569,7 +569,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -577,7 +577,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 2613bf73d..73af62aed 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ The same way you can specify a response model, you can also declare the HTTP sta * etc. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note @@ -77,7 +77,7 @@ To know more about each status code and which code is for what, check the ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ When using `Field()` with Pydantic models, you can also declare additional `exam //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ When using `Field()` with Pydantic models, you can also declare additional `exam //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ You can use it like this: //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ You can use it like this: //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ You can use it like this: //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index d1fe0163e..ead2aa799 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ Copy the example in a file `main.py`: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Copy the example in a file `main.py`: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -185,7 +185,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -229,7 +229,7 @@ Now you can pass that `oauth2_scheme` in a dependency with `Depends`. //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -237,7 +237,7 @@ Now you can pass that `oauth2_scheme` in a dependency with `Depends`. //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -251,7 +251,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 7faaa3e13..069806621 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -5,7 +5,7 @@ In the previous chapter the security system (which is based on the dependency in //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -13,7 +13,7 @@ In the previous chapter the security system (which is based on the dependency in //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -27,7 +27,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -45,7 +45,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.10+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -53,7 +53,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.9+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.8+ ```Python hl_lines="5 13-17" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -89,7 +89,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.10+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -115,7 +115,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.9+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -123,7 +123,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.8+ ```Python hl_lines="26" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -137,7 +137,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -171,7 +171,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -179,7 +179,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="20-23 27-28" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -207,7 +207,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -219,7 +219,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.10+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -227,7 +227,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.9+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -235,7 +235,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.8+ ```Python hl_lines="32" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -249,7 +249,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -263,7 +263,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -323,7 +323,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.10+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.9+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.8+ ```Python hl_lines="31-33" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -353,7 +353,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -367,7 +367,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index ba2bfef29..f454a8b28 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -119,7 +119,7 @@ And another one to authenticate and return a user. //// tab | Python 3.10+ ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -127,7 +127,7 @@ And another one to authenticate and return a user. //// tab | Python 3.9+ ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -135,7 +135,7 @@ And another one to authenticate and return a user. //// tab | Python 3.8+ ```Python hl_lines="8 50 57-58 61-62 71-77" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -149,7 +149,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -205,7 +205,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.10+ ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -213,7 +213,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.9+ ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -221,7 +221,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.8+ ```Python hl_lines="4 7 14-16 30-32 80-88" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -235,7 +235,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -249,7 +249,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -265,7 +265,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.10+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -273,7 +273,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.9+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -281,7 +281,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.8+ ```Python hl_lines="91-108" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -295,7 +295,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -309,7 +309,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -323,7 +323,7 @@ Create a real JWT access token and return it. //// tab | Python 3.10+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ Create a real JWT access token and return it. //// tab | Python 3.9+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ Create a real JWT access token and return it. //// tab | Python 3.8+ ```Python hl_lines="119-134" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -353,7 +353,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -367,7 +367,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="116-131" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index c9f6a1382..dc15bef20 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.10+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -63,7 +63,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.9+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -71,7 +71,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.8+ ```Python hl_lines="4 79" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -85,7 +85,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -99,7 +99,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -153,7 +153,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.10+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -161,7 +161,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.9+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -169,7 +169,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.8+ ```Python hl_lines="3 80-82" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -197,7 +197,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.10+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.9+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.8+ ```Python hl_lines="83-86" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -321,7 +321,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.10+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -329,7 +329,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.9+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -337,7 +337,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.8+ ```Python hl_lines="88" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -351,7 +351,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -365,7 +365,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -397,7 +397,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.10+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -405,7 +405,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.9+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -413,7 +413,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.8+ ```Python hl_lines="59-67 70-75 95" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -427,7 +427,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="56-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -441,7 +441,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 56971bf9d..f65fa773c 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -122,13 +122,13 @@ Let's refer to the file `sql_app/database.py`. ### Import the SQLAlchemy parts ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### Create a database URL for SQLAlchemy ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database). @@ -158,7 +158,7 @@ The first step is to create a SQLAlchemy "engine". We will later use this `engine` in other places. ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### Note @@ -196,7 +196,7 @@ We will use `Session` (the one imported from SQLAlchemy) later. To create the `SessionLocal` class, use the function `sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### Create a `Base` class @@ -206,7 +206,7 @@ Now we will use the function `declarative_base()` that returns a class. Later we will inherit from this class to create each of the database models or classes (the ORM models): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## Create the database models @@ -232,7 +232,7 @@ Create classes that inherit from it. These classes are the SQLAlchemy models. ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models. @@ -248,7 +248,7 @@ We use `Column` from SQLAlchemy as the default value. And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument. ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### Create the relationships @@ -260,7 +260,7 @@ For this, we use `relationship` provided by SQLAlchemy ORM. This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one. ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table. @@ -478,7 +478,7 @@ Create utility functions to: * Read multiple items. ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -499,7 +499,7 @@ The steps are: * `refresh` your instance (so that it contains any new data from the database, like the generated ID). ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// info @@ -752,13 +752,13 @@ For example, in a background task worker with ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -137,7 +137,7 @@ Both *path operations* require an `X-Token` header. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -145,7 +145,7 @@ Both *path operations* require an `X-Token` header. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -159,7 +159,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -173,7 +173,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. You could then update `test_main.py` with the extended tests: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 5161b891b..a18af2022 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -305,7 +305,6 @@ markdown_extensions: # Other extensions mdx_include: - base_path: docs extra: analytics: diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 664604c59..4a0625c25 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning | Advertencia diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 18f96213f..f6813f0ff 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de p En este caso tendrías que asegurarte de que sea único para cada operación. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Usando el nombre de la *función de la operación de path* en el operationId @@ -23,7 +23,7 @@ Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iter Deberías hacerlo después de adicionar todas tus *operaciones de path*. ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | Consejo @@ -45,7 +45,7 @@ Incluso si están en diferentes módulos (archivos Python). Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Descripción avanzada desde el docstring @@ -57,5 +57,5 @@ Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trun No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index ecd9fad41..ddfd05a77 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *función de la operació Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 4eeab3fd0..8800d2510 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primer Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: ```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | Detalles Técnicos @@ -57,7 +57,7 @@ Digamos que quieres devolver una respuesta documentación de Strawberry. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index c873385bc..156907ad1 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -23,7 +23,7 @@ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al s Comencemos con un ejemplo simple: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Llamar este programa nos muestra el siguiente output: @@ -39,7 +39,7 @@ La función hace lo siguiente: * Las concatena con un espacio en la mitad. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edítalo @@ -83,7 +83,7 @@ Eso es todo. Esos son los "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` No es lo mismo a declarar valores por defecto, como sería con: @@ -113,7 +113,7 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -123,7 +123,7 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Declarando tipos @@ -144,7 +144,7 @@ Por ejemplo, puedes usar: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tipos con sub-tipos @@ -162,7 +162,7 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -172,7 +172,7 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -192,7 +192,7 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Esto significa: @@ -209,7 +209,7 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Esto significa: @@ -225,13 +225,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Entonces puedes declarar una variable que sea de tipo `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Una vez más tendrás todo el soporte del editor: @@ -253,7 +253,7 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` /// info | Información diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 3eaea31f9..e858e34e8 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ Primero importa `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primero importa `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Primero importa `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 8d8909b97..68df00e64 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Un archivo muy simple de FastAPI podría verse así: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copia eso a un archivo `main.py`. @@ -134,7 +134,7 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. @@ -150,7 +150,7 @@ También puedes usar toda la funcionalidad de parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -164,7 +164,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : ```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -174,7 +174,7 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML : ```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` /// tip | "Astuce" diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 49ca32230..80876bc18 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse : ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Détails techniques" @@ -57,7 +57,7 @@ Disons que vous voulez retourner une réponse chaîne de caractères grâce à `str(age)` : ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Déclarer des types @@ -146,7 +146,7 @@ Comme par exemple : * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Types génériques avec des paramètres de types @@ -164,7 +164,7 @@ Par exemple, définissons une variable comme `list` de `str`. Importez `List` (avec un `L` majuscule) depuis `typing`. ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Déclarez la variable, en utilisant la syntaxe des deux-points (`:`). @@ -174,7 +174,7 @@ Et comme type, mettez `List`. Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) : ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Astuce" @@ -202,7 +202,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider C'est le même fonctionnement pour déclarer un `tuple` ou un `set` : ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Dans cet exemple : @@ -217,7 +217,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`). ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Dans cet exemple : @@ -231,7 +231,7 @@ Dans cet exemple : Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`. @@ -256,13 +256,13 @@ Vous pouvez aussi déclarer une classe comme type d'une variable. Disons que vous avez une classe `Person`, avec une variable `name` : ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Vous pouvez ensuite déclarer une variable de type `Person` : ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Et vous aurez accès, encore une fois, au support complet offert par l'éditeur : @@ -284,7 +284,7 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant. Extrait de la documentation officielle de **Pydantic** : ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index f7cf1a6cc..d971d293d 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -17,7 +17,7 @@ Cela comprend, par exemple : Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré. ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. @@ -33,7 +33,7 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal. ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Ajouter une tâche d'arrière-plan @@ -42,7 +42,7 @@ Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de t ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` reçoit comme arguments : @@ -58,7 +58,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép **FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan : ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md index fd8e5d688..dafd869e3 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ Mais vous pouvez également déclarer plusieurs paramètres provenant de body, p //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ Mais vous pouvez également déclarer plusieurs paramètres provenant de body, p //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -138,7 +138,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -146,7 +146,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -154,7 +154,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -168,7 +168,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -182,7 +182,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -228,7 +228,7 @@ Par exemple : //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -236,7 +236,7 @@ Par exemple : //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -244,7 +244,7 @@ Par exemple : //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -258,7 +258,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -272,7 +272,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -300,7 +300,7 @@ Voici un exemple complet : //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -308,7 +308,7 @@ Voici un exemple complet : //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -316,7 +316,7 @@ Voici un exemple complet : //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -330,7 +330,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -344,7 +344,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 9a5121f10..96fff2ca6 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -23,7 +23,7 @@ Ceci étant découragé, la documentation interactive générée par Swagger UI Commencez par importer la classe `BaseModel` du module `pydantic` : ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Créez votre modèle de données @@ -33,7 +33,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B Utilisez les types Python standard pour tous les attributs : ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut. @@ -63,7 +63,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête : ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...et déclarez que son type est le modèle que vous avez créé : `Item`. @@ -132,7 +132,7 @@ Ce qui améliore le support pour les modèles Pydantic avec : Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement : ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Corps de la requête + paramètres de chemin @@ -142,7 +142,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la **FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Corps de la requête + paramètres de chemin et de requête @@ -152,7 +152,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Les paramètres de la fonction seront reconnus comme tel : diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index bcd780a82..914277699 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Vous pouvez connecter le débogueur da Dans votre application FastAPI, importez et exécutez directement `uvicorn` : ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### À propos de `__name__ == "__main__"` diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index bf476d990..e9511b029 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copiez ce code dans un fichier nommé `main.py`. @@ -135,7 +135,7 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les ### Étape 1 : import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. @@ -151,7 +151,7 @@ Vous pouvez donc aussi utiliser toutes les fonctionnalités de ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -173,7 +173,7 @@ Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce pr //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -181,7 +181,7 @@ Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce pr //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -210,7 +210,7 @@ Passez `*`, comme premier paramètre de la fonction. Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` # Avec `Annotated` @@ -220,7 +220,7 @@ Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas l //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -228,7 +228,7 @@ Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas l //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -242,7 +242,7 @@ Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`q //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -250,7 +250,7 @@ Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`q //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -264,7 +264,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -279,7 +279,7 @@ La même chose s'applique pour : //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -287,7 +287,7 @@ La même chose s'applique pour : //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -301,7 +301,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -316,7 +316,7 @@ La même chose s'applique pour : //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -324,7 +324,7 @@ La même chose s'applique pour : //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -338,7 +338,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -356,7 +356,7 @@ Et la même chose pour lt. //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -364,7 +364,7 @@ Et la même chose pour lt. //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -378,7 +378,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 94c36a20d..34012c278 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -5,7 +5,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`. @@ -23,7 +23,7 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` Ici, `item_id` est déclaré comme `int`. @@ -132,7 +132,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -150,7 +150,7 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info @@ -170,7 +170,7 @@ Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Documentation @@ -188,7 +188,7 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération. Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` : ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Récupérer la *valeur de l'énumération* @@ -196,7 +196,7 @@ Vous pouvez comparer ce paramètre avec les membres de votre énumération `Mode Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` : ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "Astuce" @@ -212,7 +212,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` Le client recevra une réponse JSON comme celle-ci : @@ -253,7 +253,7 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat Vous pouvez donc l'utilisez comme tel : ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "Astuce" diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index 63578ec40..b71d1548a 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ Commençons avec cette application pour exemple : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. @@ -27,7 +27,7 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es Pour cela, importez d'abord `Query` depuis `fastapi` : ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## Utiliser `Query` comme valeur par défaut @@ -35,7 +35,7 @@ Pour cela, importez d'abord `Query` depuis `fastapi` : Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. @@ -87,7 +87,7 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son Vous pouvez aussi rajouter un second paramètre `min_length` : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## Ajouter des validations par expressions régulières @@ -95,7 +95,7 @@ Vous pouvez aussi rajouter un second paramètre `min_length` : On peut définir une expression régulière à laquelle le paramètre doit correspondre : ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` Cette expression régulière vérifie que la valeur passée comme paramètre : @@ -115,7 +115,7 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "Rappel" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info @@ -165,7 +165,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` Ce qui fait qu'avec une URL comme : @@ -202,7 +202,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` Si vous allez à : @@ -229,7 +229,7 @@ et la réponse sera : Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note @@ -257,13 +257,13 @@ Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnée Vous pouvez ajouter un `title` : ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` Et une `description` : ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## Alias de paramètres @@ -285,7 +285,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`... Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## Déprécier des paramètres @@ -297,7 +297,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti On utilise alors l'argument `deprecated=True` de `Query` : ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` La documentation le présentera comme il suit : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index b9f1540c9..c847a8f5b 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`. @@ -64,7 +64,7 @@ Les valeurs des paramètres de votre fonction seront : De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` : ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. @@ -88,7 +88,7 @@ Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira : ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` Avec ce code, en allant sur : @@ -132,7 +132,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique. Ils seront détectés par leurs noms : ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## Paramètres de requête requis @@ -144,7 +144,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut : ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`. @@ -190,7 +190,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels : ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` Ici, on a donc 3 paramètres de requête : diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index 622affa6e..904d539e7 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。 ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning | "注意" diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index a7ce6b54d..88269700e 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -25,7 +25,7 @@ 使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info | "情報" @@ -52,7 +52,7 @@ * *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info | "情報" @@ -72,7 +72,7 @@ 上記と同じ例において、 `HTMLResponse` を返すと、このようになります: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning | "注意" @@ -98,7 +98,7 @@ 例えば、このようになります: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。 @@ -139,7 +139,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -151,7 +151,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -175,7 +175,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip | "豆知識" @@ -189,7 +189,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。 ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` ### `StreamingResponse` @@ -197,7 +197,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。 ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### `StreamingResponse` をファイルライクなオブジェクトとともに使う @@ -207,7 +207,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。 ```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` /// tip | "豆知識" @@ -230,7 +230,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。 ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` ## デフォルトレスポンスクラス @@ -242,7 +242,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。 ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index ae60126cb..2dab4aec1 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ `operation_id` は各オペレーションで一意にする必要があります。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### *path operation関数* の名前をoperationIdとして使用する @@ -23,7 +23,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP そうする場合は、すべての *path operation* を追加した後に行う必要があります。 ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | "豆知識" @@ -45,7 +45,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP 生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstringによる説明の高度な設定 @@ -57,5 +57,5 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。 ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 5c25471b1..167d15589 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。 ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "技術詳細" @@ -57,7 +57,7 @@ XMLを文字列にし、`Response` に含め、それを返します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 備考 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 615f9d17c..f7bcb6af3 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -39,7 +39,7 @@ $ pip install websockets しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。 ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## `websocket` を作成する @@ -47,7 +47,7 @@ $ pip install websockets **FastAPI** アプリケーションで、`websocket` を作成します。 ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "技術詳細" @@ -63,7 +63,7 @@ $ pip install websockets WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` バイナリやテキストデータ、JSONデータを送受信できます。 @@ -116,7 +116,7 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。 ```Python hl_lines="58-65 68-83" -{!../../../docs_src/websockets/tutorial002.py!} +{!../../docs_src/websockets/tutorial002.py!} ``` /// info | "情報" @@ -165,7 +165,7 @@ $ uvicorn main:app --reload WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。 ```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} +{!../../docs_src/websockets/tutorial003.py!} ``` 試してみるには、 diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index b892ed6c6..053d481f7 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ 例えば、 ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index 730a209ab..7af6ce0c0 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -23,7 +23,7 @@ 簡単な例から始めてみましょう: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` このプログラムを実行すると以下が出力されます: @@ -39,7 +39,7 @@ John Doe * 真ん中にスペースを入れて連結します。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 編集 @@ -83,7 +83,7 @@ John Doe それが「型ヒント」です: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -113,7 +113,7 @@ John Doe この関数を見てください。すでに型ヒントを持っています: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -123,7 +123,7 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 型の宣言 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 型パラメータを持つジェネリック型 @@ -162,7 +162,7 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -172,7 +172,7 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "豆知識" @@ -200,7 +200,7 @@ John Doe `tuple`と`set`の宣言も同様です: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` つまり: @@ -218,7 +218,7 @@ John Doe 2番目の型パラメータは`dict`の値です。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` つまり: @@ -232,7 +232,7 @@ John Doe また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 @@ -257,13 +257,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: ```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 変数の型を`Person`として宣言することができます: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` そして、再び、すべてのエディタのサポートを得ることができます: @@ -285,7 +285,7 @@ John Doe Pydanticの公式ドキュメントから引用: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "情報" diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 6094c370f..6f9340817 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 @@ -34,7 +34,7 @@ また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## バックグラウンドタスクの追加 @@ -42,7 +42,7 @@ *path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` は以下の引数を受け取ります: @@ -58,7 +58,7 @@ **FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index b9f6d694b..1d386040a 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -7,7 +7,7 @@ まず、以下のようにインポートします: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` /// warning | "注意" @@ -21,7 +21,7 @@ 以下のように`Field`をモデルの属性として使用することができます: ```Python hl_lines="11 12 13 14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index c051fde24..647143ee5 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -9,7 +9,7 @@ また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: ```Python hl_lines="19 20 21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` /// note | "備考" @@ -34,7 +34,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -78,7 +78,7 @@ ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: @@ -115,7 +115,7 @@ q: str = None 以下において: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` /// info | "情報" @@ -139,7 +139,7 @@ item: Item = Body(..., embed=True) 以下において: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 59ee67295..8703a40e7 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ 属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: ```Python hl_lines="12" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 @@ -21,7 +21,7 @@ まず、Pythonの標準の`typing`モジュールから`List`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### タイプパラメータを持つ`List`の宣言 @@ -44,7 +44,7 @@ my_list: List[str] そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## セット型 @@ -56,7 +56,7 @@ my_list: List[str] そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 @@ -80,7 +80,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルを定義することができます: ```Python hl_lines="9 10 11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### サブモデルを型として使用 @@ -88,7 +88,7 @@ Pydanticモデルの各属性には型があります。 そして、それを属性の型として使用することができます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` これは **FastAPI** が以下のようなボディを期待することを意味します: @@ -123,7 +123,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 @@ -133,7 +133,7 @@ Pydanticモデルの各属性には型があります。 Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): @@ -173,7 +173,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する 深くネストされた任意のモデルを定義することができます: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` /// info | "情報" @@ -193,7 +193,7 @@ images: List[Image] 以下のように: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## あらゆる場所でのエディタサポート @@ -225,7 +225,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 672a03a64..fde9f4f5e 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 ```Python hl_lines="30 31 32 33 34 35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -57,7 +57,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### Pydanticの`update`パラメータ @@ -67,7 +67,7 @@ `stored_item_model.copy(update=update_data)`のように: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 部分的更新のまとめ @@ -86,7 +86,7 @@ * 更新されたモデルを返します。 ```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 017ff8986..888d4388a 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -23,7 +23,7 @@ GET リクエストでボディを送信することは、仕様では未定義 ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: ```Python hl_lines="2" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## データモデルの作成 @@ -33,7 +33,7 @@ GET リクエストでボディを送信することは、仕様では未定義 すべての属性にpython標準の型を使用します: ```Python hl_lines="5-9" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -63,7 +63,7 @@ GET リクエストでボディを送信することは、仕様では未定義 *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: ```Python hl_lines="16" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...そして、作成したモデル `Item` で型を宣言します。 @@ -132,7 +132,7 @@ GET リクエストでボディを送信することは、仕様では未定義 関数内部で、モデルの全ての属性に直接アクセスできます: ```Python hl_lines="19" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## リクエストボディ + パスパラメータ @@ -142,7 +142,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 ```Python hl_lines="15-16" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -152,7 +152,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 ```Python hl_lines="16" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` 関数パラメータは以下の様に認識されます: diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 212885209..1f45db17c 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -7,7 +7,7 @@ まず、`Cookie`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` ## `Cookie`のパラメータを宣言 @@ -17,7 +17,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` /// note | "技術詳細" diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 738240342..9530c51bf 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 06b8ad277..be0ff81d4 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### `__name__ == "__main__"` について diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 69b67d042..fb23a7b2b 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -7,7 +7,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: ```Python hl_lines="9" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -72,19 +72,19 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: ```Python hl_lines="11 12 13 14 15" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: ```Python hl_lines="12" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` ...以前の`common_parameters`と同じパラメータを持っています: ```Python hl_lines="8" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -102,7 +102,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -144,7 +144,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial003.py!} +{!../../docs_src/dependencies/tutorial003.py!} ``` しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -180,7 +180,7 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial004.py!} +{!../../docs_src/dependencies/tutorial004.py!} ``` ...そして **FastAPI** は何をすべきか知っています。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c6472cab5..59f21c3df 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ それは`Depends()`の`list`であるべきです: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 @@ -39,7 +39,7 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 例外の発生 @@ -47,7 +47,7 @@ これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 戻り値 @@ -57,7 +57,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 3f22a7a7b..7ef1caf0d 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -42,19 +42,19 @@ pip install async-exit-stack async-generator レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 ```Python hl_lines="2 3 4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` 生成された値は、*path operations*や他の依存関係に注入されるものです: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` `yield`文に続くコードは、レスポンスが送信された後に実行されます: ```Python hl_lines="5 6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "豆知識" @@ -76,7 +76,7 @@ pip install async-exit-stack async-generator 同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## `yield`を持つサブ依存関係 @@ -88,7 +88,7 @@ pip install async-exit-stack async-generator 例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: ```Python hl_lines="4 12 20" -{!../../../docs_src/dependencies/tutorial008.py!} +{!../../docs_src/dependencies/tutorial008.py!} ``` そして、それらはすべて`yield`を使用することができます。 @@ -98,7 +98,7 @@ pip install async-exit-stack async-generator そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 ```Python hl_lines="16 17 24 25" -{!../../../docs_src/dependencies/tutorial008.py!} +{!../../docs_src/dependencies/tutorial008.py!} ``` 同様に、`yield`と`return`が混在した依存関係を持つこともできます。 @@ -234,7 +234,7 @@ Pythonでは、`typing.Union`を使用します: ```Python hl_lines="1 14 15 18 19 20 33" -{!../../../docs_src/extra_models/tutorial003.py!} +{!../../docs_src/extra_models/tutorial003.py!} ``` ## モデルのリスト @@ -179,7 +179,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準のPythonの`typing.List`を使用する: ```Python hl_lines="1 20" -{!../../../docs_src/extra_models/tutorial004.py!} +{!../../docs_src/extra_models/tutorial004.py!} ``` ## 任意の`dict`を持つレスポンス @@ -191,7 +191,7 @@ OpenAPIでは`anyOf`で定義されます。 この場合、`typing.Dict`を使用することができます: ```Python hl_lines="1 8" -{!../../../docs_src/extra_models/tutorial005.py!} +{!../../docs_src/extra_models/tutorial005.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index dbe8e4518..77f3b5fbe 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これを`main.py`にコピーします。 @@ -134,7 +134,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 @@ -150,7 +150,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 2: `FastAPI`の「インスタンス」を生成 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 @@ -171,7 +171,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -250,7 +250,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: @@ -305,7 +305,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これは、Pythonの関数です。 @@ -319,7 +319,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ `async def`の代わりに通常の関数として定義することもできます: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "備考" @@ -331,7 +331,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ ### Step 5: コンテンツの返信 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 8be054858..e94f16b21 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ HTTPレスポンスをエラーでクライアントに返すには、`HTTPExcep ### `HTTPException`のインポート ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### コード内での`HTTPException`の発生 @@ -42,7 +42,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### レスポンス結果 @@ -82,7 +82,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## カスタム例外ハンドラのインストール @@ -96,7 +96,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: ```Python hl_lines="5 6 7 13 14 15 16 17 18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 @@ -136,7 +136,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例外ハンドラは`Requset`と例外を受け取ります。 ```Python hl_lines="2 14 15 16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: @@ -189,7 +189,7 @@ path -> item_id 例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: ```Python hl_lines="3 4 9 10 11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "技術詳細" @@ -207,7 +207,7 @@ path -> item_id アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` ここで、以下のような無効な項目を送信してみてください: @@ -269,7 +269,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: ```Python hl_lines="2 3 4 5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` この例では、非常に表現力のあるメッセージでエラーを`print`しています。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 4fab3d423..3180b78b5 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ まず、`Header`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header`のパラメータの宣言 @@ -17,7 +17,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` /// note | "技術詳細" @@ -51,7 +51,7 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` /// warning | "注意" @@ -71,7 +71,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index eb85dc389..8285b479e 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -14,7 +14,7 @@ これらを設定するには、パラメータ `title`、`description`、`version` を使用します: ```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` この設定では、自動APIドキュメントは以下の様になります: @@ -42,7 +42,7 @@ タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 @@ -58,7 +58,7 @@ `tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info | "情報" @@ -88,7 +88,7 @@ たとえば、`/api/v1/openapi.json` で提供されるように設定するには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 @@ -107,5 +107,5 @@ OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 05e1b7a8c..f4a503720 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * その後、`response` を返す前にさらに `response` を変更することもできます。 ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "豆知識" @@ -60,7 +60,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index def12bd08..7eceb377d 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -17,7 +17,7 @@ しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 @@ -35,7 +35,7 @@ `tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: @@ -47,7 +47,7 @@ `summary`と`description`を追加できます: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## docstringを用いた説明 @@ -57,7 +57,7 @@ docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` これは対話的ドキュメントで使用されます: @@ -69,7 +69,7 @@ docstringにdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` 対話的ドキュメントでは非推奨と明記されます: diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 9f0b72585..42fbb2ee2 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ まず初めに、`fastapi`から`Path`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## メタデータの宣言 @@ -17,7 +17,7 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` /// note | "備考" @@ -47,7 +47,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 必要に応じてパラメータを並び替えるトリック @@ -59,7 +59,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 数値の検証: 以上 @@ -69,7 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 数値の検証: より大きいと小なりイコール @@ -80,7 +80,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `le`: 小なりイコール(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 数値の検証: 浮動小数点、 大なり小なり @@ -94,7 +94,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 0a7916012..e1cb67a13 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: ```Python hl_lines="6 7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -19,7 +19,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` ここでは、 `item_id` は `int` として宣言されています。 @@ -122,7 +122,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -140,7 +140,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: ```Python hl_lines="1 6 7 8 9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "情報" @@ -160,7 +160,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ドキュメントの確認 @@ -178,7 +178,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *列挙値*の取得 @@ -186,7 +186,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "豆知識" @@ -202,7 +202,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` クライアントは以下の様なJSONレスポンスを得ます: @@ -243,7 +243,7 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index ada048844..9e54a6f55 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ 以下のアプリケーションを例にしてみましょう: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 @@ -27,7 +27,7 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で そのために、まずは`fastapi`から`Query`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## デフォルト値として`Query`を使用 @@ -35,7 +35,7 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -87,7 +87,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 正規表現の追加 @@ -95,7 +95,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータが一致するべき正規表現を定義することができます: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -115,7 +115,7 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "備考" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "情報" @@ -165,7 +165,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` そしてURLは以下です: @@ -202,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 以下のURLを開くと: @@ -227,7 +227,7 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "備考" @@ -255,13 +255,13 @@ http://localhost:8000/items/ `title`を追加できます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` `description`を追加できます: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## エイリアスパラメータ @@ -283,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 非推奨パラメータ @@ -295,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index c0eb2d096..6d41d3742 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -64,7 +64,7 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 @@ -80,7 +80,7 @@ http://127.0.0.1:8000/items/?skip=20 `bool` 型も宣言できます。これは以下の様に変換されます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` この場合、以下にアクセスすると: @@ -124,7 +124,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 必須のクエリパラメータ @@ -136,7 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -182,7 +182,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` この場合、3つのクエリパラメータがあります。: diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index d8effc219..e03b9166d 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## `File`と`Form`のインポート ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## `File`と`Form`のパラメータの定義 @@ -21,7 +21,7 @@ ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index d04dc810b..eb453c04a 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `fastapi`から`Form`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## `Form`のパラメータの定義 @@ -23,7 +23,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Body`や`Query`の場合と同じようにフォームパラメータを作成します: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 7bb5e2825..973f893de 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -9,7 +9,7 @@ * など。 ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` /// note | "備考" @@ -42,13 +42,13 @@ FastAPIは`response_model`を使って以下のことをします: ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: ```Python hl_lines="17 18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -68,19 +68,19 @@ FastAPIは`response_model`を使って以下のことをします: 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -100,7 +100,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: ```Python hl_lines="11 13 14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: str = None`は`None`がデフォルト値です。 @@ -116,7 +116,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -206,7 +206,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d /// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` /// tip | "豆知識" @@ -222,7 +222,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 945767894..90b290887 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * など。 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "備考" @@ -77,7 +77,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス 先ほどの例をもう一度見てみましょう: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201`は「作成完了」のためのステータスコードです。 @@ -87,7 +87,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index a3cd5eb54..baf1bbedd 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: ```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -21,7 +21,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: ```Python hl_lines="4 10 11 12 13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` /// warning | "注意" @@ -37,7 +37,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: ```Python hl_lines="21 22 23 24 25 26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index c78a3755e..51f7bf829 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -21,7 +21,7 @@ `main.py`に、下記の例をコピーします: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 実行 @@ -129,7 +129,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip | "豆知識" @@ -169,7 +169,7 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 250f66b81..0edbd983f 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` しかし、それはまだそんなに有用ではありません。 @@ -17,7 +17,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: ```Python hl_lines="5 12-16" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 依存関係 `get_current_user` を作成 @@ -31,7 +31,7 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: ```Python hl_lines="25" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## ユーザーの取得 @@ -39,7 +39,7 @@ `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: ```Python hl_lines="19-22 26-27" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 現在のユーザーの注入 @@ -47,7 +47,7 @@ ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 ```Python hl_lines="31" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 @@ -104,7 +104,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: ```Python hl_lines="30-32" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 4f6aebd4c..b2f511610 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -119,7 +119,7 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ さらに、ユーザーを認証して返す関数も作成します。 ```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` /// note | "備考" @@ -157,7 +157,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 ```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## 依存関係の更新 @@ -169,7 +169,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 ```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## `/token` パスオペレーションの更新 @@ -179,7 +179,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 ```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ### JWTの"subject" `sub` についての技術的な詳細 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index c9d95bc34..e6002a1fb 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "技術詳細" diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 3ed03ebea..6c5e712e8 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -19,7 +19,7 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "豆知識" @@ -57,7 +57,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ **FastAPI** アプリに `main.py` ファイルがあるとします: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### テストファイル @@ -65,7 +65,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: ```Python -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ## テスト: 例の拡張 @@ -86,7 +86,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -94,7 +94,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ //// tab | Python 3.6+ ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -104,7 +104,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index e155f41f1..94867c198 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -15,7 +15,7 @@ 응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. @@ -29,7 +29,7 @@ 응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 5c458e48d..6d7346189 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -23,7 +23,7 @@ 간단한 예제부터 시작해봅시다: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 이 프로그램을 실행한 결과값: @@ -39,7 +39,7 @@ John Doe * 두 단어를 중간에 공백을 두고 연결합니다. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 코드 수정 @@ -83,7 +83,7 @@ John Doe 이게 "타입 힌트"입니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -113,7 +113,7 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -123,7 +123,7 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 타입 선언 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -162,7 +162,7 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -172,7 +172,7 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "팁" @@ -200,7 +200,7 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 이 뜻은 아래와 같습니다: @@ -217,7 +217,7 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 이 뜻은 아래와 같습니다: @@ -231,7 +231,7 @@ John Doe `str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다. @@ -256,13 +256,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -284,7 +284,7 @@ John Doe Pydantic 공식 문서 예시: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "정보" diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 880a1c198..376c52524 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -34,7 +34,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 백그라운드 작업 추가 @@ -42,7 +42,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -60,7 +60,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ //// tab | Python 3.6 and above ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// @@ -68,7 +68,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ //// tab | Python 3.10 and above ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index b74722e26..a13159c27 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 023575e1b..0a0f34585 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. ```Python hl_lines="19-21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` /// note | "참고" @@ -36,7 +36,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -80,7 +80,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -111,7 +111,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` 이렇게: @@ -135,7 +135,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 4d785f64b..12fb4e0cc 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -6,7 +6,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -20,7 +20,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### 타입 매개변수로 `List` 선언 @@ -43,7 +43,7 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## 집합 타입 @@ -55,7 +55,7 @@ my_list: List[str] 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -79,7 +79,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### 서브모듈을 타입으로 사용 @@ -87,7 +87,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -122,7 +122,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -132,7 +132,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -172,7 +172,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` /// info | "정보" @@ -192,7 +192,7 @@ images: List[Image] 이를 아래처럼: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## 어디서나 편집기 지원 @@ -224,7 +224,7 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` /// tip | "팁" diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 337218eb4..8df8d556e 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 5f129b63f..1e21e069d 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 312fdee1b..65357ae3f 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index cb45e5169..27e8f9abf 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### `__name__ == "__main__"` 에 대하여 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 259fe4b6d..7430efbb4 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | 파이썬 3.6 이상 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 파이썬 3.10 이상 ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -84,7 +84,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -92,7 +92,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -102,7 +102,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -110,7 +110,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -120,7 +120,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -128,7 +128,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -150,7 +150,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -158,7 +158,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -203,7 +203,7 @@ commons = Depends(CommonQueryParams) //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -211,7 +211,7 @@ commons = Depends(CommonQueryParams) //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -251,7 +251,7 @@ commons: CommonQueryParams = Depends() //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// @@ -259,7 +259,7 @@ commons: CommonQueryParams = Depends() //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index bc8af488d..e71ba8546 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 2ce2cf4f2..dd6586c3e 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index 361989e2b..f7b2f1788 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index b8e87449c..732566d6d 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -21,7 +21,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: ```Python hl_lines="5 22" -{!../../../docs_src/encoder/tutorial001.py!} +{!../../docs_src/encoder/tutorial001.py!} ``` 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index df3c7a06e..8baaa64fc 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index 52e53fd89..c2c48fb3e 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 위 코드를 `main.py`에 복사합니다. @@ -134,7 +134,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. @@ -150,7 +150,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 2 단계: `FastAPI` "인스턴스" 생성 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -251,7 +251,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. @@ -307,7 +307,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 이것은 파이썬 함수입니다. @@ -321,7 +321,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa `async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "참고" @@ -333,7 +333,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ### 5 단계: 콘텐츠 반환 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index d403b9175..26e198869 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ 먼저 `Header`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header` 매개변수 선언 @@ -17,7 +17,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` /// note | "기술 세부사항" @@ -51,7 +51,7 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: ```Python hl_lines="10" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` /// warning | "경고" @@ -71,7 +71,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index 84f67bd26..f36f11a27 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "팁" @@ -60,7 +60,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index b6608a14d..6ebe613a8 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -17,7 +17,7 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. @@ -35,7 +35,7 @@ (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -47,7 +47,7 @@ `summary`와 `description`을 추가할 수 있습니다: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## 독스트링으로 만든 기술 @@ -57,7 +57,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` 이는 대화형 문서에서 사용됩니다: @@ -69,7 +69,7 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: ```Python hl_lines="21" -{!../../../docs_src/path_operation_configuration/tutorial005.py!} +{!../../docs_src/path_operation_configuration/tutorial005.py!} ``` /// info | "정보" @@ -93,7 +93,7 @@ OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index 6d3215c24..caab2d453 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## 메타데이터 선언 @@ -17,7 +17,7 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` /// note | "참고" @@ -47,7 +47,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -59,7 +59,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 숫자 검증: 크거나 같음 @@ -69,7 +69,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -80,7 +80,7 @@ * `le`: 작거나 같은(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -94,7 +94,7 @@ lt 역시 마찬가지입니다. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 요약 diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 67a2d899d..09a27a7b3 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -19,7 +19,7 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 위의 예시에서, `item_id`는 `int`로 선언되었습니다. @@ -122,7 +122,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -140,7 +140,7 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "정보" @@ -160,7 +160,7 @@ 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### 문서 확인 @@ -178,7 +178,7 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *열거형 값* 가져오기 @@ -186,7 +186,7 @@ `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "팁" @@ -202,7 +202,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -243,7 +243,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "팁" diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 11193950b..e44f6dd16 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ 이 응용 프로그램을 예로 들어보겠습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. @@ -27,7 +27,7 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## 기본값으로 `Query` 사용 @@ -35,7 +35,7 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -87,7 +87,7 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 정규식 추가 @@ -95,7 +95,7 @@ q: str = Query(None, max_length=50) 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -115,7 +115,7 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "참고" @@ -147,7 +147,7 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "정보" @@ -165,7 +165,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` 아래와 같은 URL을 사용합니다: @@ -202,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 아래로 이동한다면: @@ -227,7 +227,7 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "참고" @@ -255,13 +255,13 @@ http://localhost:8000/items/ `title`을 추가할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` 그리고 `description`도 추가할 수 있습니다: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## 별칭 매개변수 @@ -283,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 매개변수 사용하지 않게 하기 @@ -295,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index e71444c18..b2a946c09 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -64,7 +64,7 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. @@ -88,7 +88,7 @@ FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` 이 경우, 아래로 이동하면: @@ -133,7 +133,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 필수 쿼리 매개변수 @@ -145,7 +145,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -191,7 +191,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` 위 예시에서는 3가지 쿼리 매개변수가 있습니다: diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index b7781ef5e..40579dd51 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -17,7 +17,7 @@ `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## `File` 매개변수 정의 @@ -25,7 +25,7 @@ `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` /// info | "정보" @@ -55,7 +55,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본 `File` 매개변수를 `UploadFile` 타입으로 정의합니다: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -143,7 +143,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: ```Python hl_lines="10 15" -{!../../../docs_src/request_files/tutorial002.py!} +{!../../docs_src/request_files/tutorial002.py!} ``` 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 0867414ea..24501fe34 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## `File` 및 `Form` 업로드 ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## `File` 및 `Form` 매개변수 정의 @@ -21,7 +21,7 @@ `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index fc74a60b3..74034e34d 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -9,7 +9,7 @@ * 기타. ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` /// note | "참고" @@ -42,13 +42,13 @@ FastAPI는 이 `response_model`를 사용하여: 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: ```Python hl_lines="17-18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -68,19 +68,19 @@ FastAPI는 이 `response_model`를 사용하여: 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -100,7 +100,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: ```Python hl_lines="11 13-14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. @@ -116,7 +116,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -208,7 +208,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 /// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` /// tip | "팁" @@ -224,7 +224,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 48cb49cbf..57eef6ba1 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * 기타 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "참고" @@ -77,7 +77,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 상기 예시 참고: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -87,7 +87,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 7b5ccdd32..71052b334 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ Pydantic v2 ```Python hl_lines="13-24" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index 9bf3d4ee1..56f5792a7 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 그러나 아직도 유용하지 않습니다. @@ -19,7 +19,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -27,7 +27,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -45,7 +45,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -53,7 +53,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -73,7 +73,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -93,7 +93,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -153,7 +153,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 //// tab | 파이썬 3.7 이상 ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -161,7 +161,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 //// tab | 파이썬 3.10 이상 ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index 9593f96f5..fd18c1d47 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ OAuth2의 경우 문자열일 뿐입니다. //// tab | 파이썬 3.7 이상 ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -63,7 +63,7 @@ OAuth2의 경우 문자열일 뿐입니다. //// tab | 파이썬 3.10 이상 ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.7 이상 ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -125,7 +125,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.10 이상 ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | P파이썬 3.7 이상 ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -165,7 +165,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.10 이상 ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -213,7 +213,7 @@ UserInDB( //// tab | 파이썬 3.7 이상 ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -221,7 +221,7 @@ UserInDB( //// tab | 파이썬 3.10 이상 ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -253,7 +253,7 @@ UserInDB( //// tab | 파이썬 3.7 이상 ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -261,7 +261,7 @@ UserInDB( //// tab | 파이썬 3.10 이상 ```Python hl_lines="55-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index 360aaaa6b..90a60d193 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "기술적 세부사항" diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md index a5562b795..00052037c 100644 --- a/docs/nl/docs/python-types.md +++ b/docs/nl/docs/python-types.md @@ -23,7 +23,7 @@ Als je een Python expert bent en alles al weet over type hints, sla dan dit hoof Laten we beginnen met een eenvoudig voorbeeld: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Het aanroepen van dit programma leidt tot het volgende resultaat: @@ -40,7 +40,7 @@ De functie voert het volgende uit: * Voeg samen met een spatie in het midden. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Bewerk het @@ -84,7 +84,7 @@ Dat is alles. Dat zijn de "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: @@ -114,7 +114,7 @@ Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt di Bekijk deze functie, deze heeft al type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: @@ -124,7 +124,7 @@ Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Types declareren @@ -145,7 +145,7 @@ Je kunt bijvoorbeeld het volgende gebruiken: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generieke types met typeparameters @@ -183,7 +183,7 @@ Als type, vul `list` in. Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -193,7 +193,7 @@ Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vie Van `typing`, importeer `List` (met een hoofdletter `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Declareer de variabele met dezelfde dubbele punt (`:`) syntax. @@ -203,7 +203,7 @@ Zet als type de `List` die je hebt geïmporteerd uit `typing`. Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -241,7 +241,7 @@ Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -249,7 +249,7 @@ Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -270,7 +270,7 @@ De tweede typeparameter is voor de waarden (values) van het `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -278,7 +278,7 @@ De tweede typeparameter is voor de waarden (values) van het `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -300,7 +300,7 @@ In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -308,7 +308,7 @@ In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -322,7 +322,7 @@ Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn. @@ -334,7 +334,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -342,7 +342,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -350,7 +350,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -371,7 +371,7 @@ Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed heb Laten we als voorbeeld deze functie nemen: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: @@ -389,7 +389,7 @@ say_hi(name=None) # Dit werkt, None is geldig 🎉 Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 @@ -453,13 +453,13 @@ Je kunt een klasse ook declareren als het type van een variabele. Stel dat je een klasse `Person` hebt, met een naam: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Vervolgens kun je een variabele van het type `Persoon` declareren: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Dan krijg je ook nog eens volledige editorondersteuning: @@ -487,7 +487,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -495,7 +495,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -503,7 +503,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -533,7 +533,7 @@ Python heeft ook een functie waarmee je **extra ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -545,7 +545,7 @@ In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensio Het wordt al geïnstalleerd met **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 8f1b9b922..99c425f12 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Najprostszy plik FastAPI może wyglądać tak: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Skopiuj to do pliku `main.py`. @@ -134,7 +134,7 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt ### Krok 1: zaimportuj `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. @@ -150,7 +150,7 @@ Oznacza to, że możesz korzystać ze wszystkich funkcjonalności ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretament //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretament //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Faça uso da versão `Annotated` quando possível. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Faça uso da versão `Annotated` quando possível. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 5a7b921b2..a656390a4 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ Para fazer isso, nós declaramos o método `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Para fazer isso, nós declaramos o método `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da inst //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da inst //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ Nós poderíamos criar uma instância desta classe com: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ Nós poderíamos criar uma instância desta classe com: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 7cac26262..c81d6124b 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante O arquivo `main.py` teria: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Executá-lo @@ -61,7 +61,7 @@ $ pytest O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip | "Dica" @@ -73,7 +73,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` Isso é equivalente a: diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 2dfc5ca25..3c65b5a0a 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`. Embora todo o seu código esteja escrito assumindo que existe apenas `/app`. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`. @@ -99,7 +99,7 @@ Você pode obter o `root_path` atual usado pela sua aplicação para cada solici Aqui estamos incluindo ele na mensagem apenas para fins de demonstração. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Então, se você iniciar o Uvicorn com: @@ -128,7 +128,7 @@ A resposta seria algo como: Alternativamente, se você não tiver uma maneira de fornecer uma opção de linha de comando como `--root-path` ou equivalente, você pode definir o parâmetro `--root-path` ao criar sua aplicação FastAPI: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Passar o `root_path`h para `FastAPI` seria o equivalente a passar a opção de linha de comando `--root-path` para Uvicorn ou Hypercorn. @@ -310,7 +310,7 @@ Se você passar uma lista personalizada de `servers` e houver um `root_path` (po Por exemplo: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Gerará um OpenAPI schema como: @@ -359,7 +359,7 @@ A interface de documentação interagirá com o servidor que você selecionar. Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` e então ele não será incluído no OpenAPI schema. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 5f722763e..02f5b6d2b 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -32,7 +32,7 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. @@ -52,7 +52,7 @@ Talvez você precise inicializar uma nova versão, ou apenas cansou de executá- A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -66,7 +66,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -90,7 +90,7 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Eventos alternativos (deprecados) @@ -114,7 +114,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -128,7 +128,7 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 2ccd0e819..5a0226c74 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md index 99695c831..2ac5eca18 100644 --- a/docs/pt/docs/advanced/response-change-status-code.md +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç E então você pode definir o `status_code` neste objeto de retorno temporal. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md index fc571d39b..fd2a0eef1 100644 --- a/docs/pt/docs/advanced/response-directly.md +++ b/docs/pt/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | Detalhes Técnicos @@ -57,7 +57,7 @@ Vamos dizer quer retornar uma resposta ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Então, quando você digitar o usuário e senha, o navegador os envia automatica //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `c //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `c //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -164,7 +164,7 @@ Após detectar que as credenciais estão incorretas, retorne um `HTTPException` //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -172,7 +172,7 @@ Após detectar que as credenciais estão incorretas, retorne um `HTTPException` //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -186,7 +186,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index 4ad7c807e..fa4594c89 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.10+ ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.9+ ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.8+ ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.10+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.9+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.8+ ```Python hl_lines="64-67" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.10+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.9+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.8+ ```Python hl_lines="157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.10+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.9+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.8+ ```Python hl_lines="5 141 172" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.10+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.9+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.8+ ```Python hl_lines="9 107" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.10+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.9+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.8+ ```Python hl_lines="107 109-117" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.10+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.9+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.8+ ```Python hl_lines="48 118-129" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.10+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.9+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.8+ ```Python hl_lines="130-136" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index db2b4c9cc..d32b70ed4 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -181,7 +181,7 @@ Você pode utilizar todas as ferramentas e funcionalidades de validação que s //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -195,7 +195,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -215,7 +215,7 @@ Depois ele irá converter e validar os dados. Assim, quando você utilizar aquel Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Executando o servidor @@ -251,13 +251,13 @@ Você também pode incluir essas configurações em um arquivo de um módulo sep Por exemplo, você pode adicionar um arquivo `config.py` com: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` E utilizar essa configuração em `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// dica @@ -277,7 +277,7 @@ Isso é especialmente útil durante os testes, já que é bastante simples sobre Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. @@ -289,7 +289,7 @@ Agora criamos a dependência que retorna um novo objeto `config.Settings()`. //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -297,7 +297,7 @@ Agora criamos a dependência que retorna um novo objeto `config.Settings()`. //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -311,7 +311,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -329,7 +329,7 @@ E então podemos declarar essas configurações como uma dependência na funçã //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -337,7 +337,7 @@ E então podemos declarar essas configurações como uma dependência na funçã //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -351,7 +351,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -361,7 +361,7 @@ Utilize a versão com `Annotated` se possível. Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. @@ -406,7 +406,7 @@ E então adicionar o seguinte código em `config.py`: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// dica @@ -420,7 +420,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// dica @@ -465,7 +465,7 @@ Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -473,7 +473,7 @@ Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -487,7 +487,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md index 8149edc5a..7f0381cc2 100644 --- a/docs/pt/docs/advanced/sub-applications.md +++ b/docs/pt/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Sub-aplicação @@ -21,7 +21,7 @@ Em seguida, crie sua sub-aplicação e suas *operações de rota*. Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Monte a sub-aplicação @@ -31,7 +31,7 @@ Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. Neste caso, ela será montada no caminho `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Verifique a documentação automática da API diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 6d231b3c2..88a5b940e 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -26,7 +26,7 @@ $ pip install jinja2 * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -56,7 +56,7 @@ Você também poderia usar `from starlette.templating import Jinja2Templates`. Então você pode escrever um template em `templates/item.html`, por exemplo: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Interpolação de Valores no Template @@ -110,13 +110,13 @@ Por exemplo, com um ID de `42`, isso renderizará: Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index 747dd7d06..f978350a5 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md index 392fb741c..b6796e835 100644 --- a/docs/pt/docs/advanced/testing-events.md +++ b/docs/pt/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index f458a05d4..daa610df6 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ Você pode usar o mesmo `TestClient` para testar WebSockets. Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Nota" diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index 3dd0a8aef..c2114c214 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro d Para isso você precisa acessar a requisição diretamente. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md index 2c7ac1ffe..e6d08c8db 100644 --- a/docs/pt/docs/advanced/wsgi.md +++ b/docs/pt/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. E então **"montar"** em um caminho de rota. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Conferindo diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md index cfa652fa5..675b812e6 100644 --- a/docs/pt/docs/how-to/conditional-openapi.md +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar Por exemplo: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index ceb8c634e..58bb1557c 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...e então o Swagger UI não mostrará mais o destaque de sintaxe: @@ -31,7 +31,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` Essa configuração alteraria o tema de cores de destaque de sintaxe: @@ -45,7 +45,7 @@ O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a Inclui estas configurações padrão: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. @@ -53,7 +53,7 @@ Você pode substituir qualquer um deles definindo um valor diferente no argument Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Outros parâmetros da UI do Swagger diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md index 0b711aa5e..2cfd790c5 100644 --- a/docs/pt/docs/how-to/graphql.md +++ b/docs/pt/docs/how-to/graphql.md @@ -36,7 +36,7 @@ Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: ```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} +{!../../docs_src/graphql/tutorial001.py!} ``` Você pode aprender mais sobre Strawberry na documentação do Strawberry. diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 86630cd2a..05faa860c 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -23,7 +23,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par Vamos começar com um exemplo simples: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` A chamada deste programa gera: @@ -39,7 +39,7 @@ A função faz o seguinte: * Concatena com um espaço no meio. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edite-o @@ -83,7 +83,7 @@ para: Esses são os "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Isso não é o mesmo que declarar valores padrão como seria com: @@ -113,7 +113,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma ca Marque esta função, ela já possui type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro: @@ -123,7 +123,7 @@ Como o editor conhece os tipos de variáveis, você não apenas obtém a conclus Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Tipos de declaração @@ -144,7 +144,7 @@ Você pode usar, por exemplo: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tipos genéricos com parâmetros de tipo @@ -162,7 +162,7 @@ Por exemplo, vamos definir uma variável para ser uma `lista` de `str`. Em `typing`, importe `List` (com um `L` maiúsculo): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Declare a variável com a mesma sintaxe de dois pontos (`:`). @@ -172,7 +172,7 @@ Como o tipo, coloque a `List`. Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Dica" @@ -200,7 +200,7 @@ E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso. Você faria o mesmo para declarar `tuple`s e `set`s: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Isso significa que: @@ -217,7 +217,7 @@ O primeiro parâmetro de tipo é para as chaves do `dict`. O segundo parâmetro de tipo é para os valores do `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Isso significa que: @@ -231,7 +231,7 @@ Isso significa que: Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. @@ -256,13 +256,13 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: ```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Então você pode declarar que uma variável é do tipo `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` E então, novamente, você recebe todo o suporte do editor: @@ -284,7 +284,7 @@ E você recebe todo o suporte do editor com esse objeto resultante. Retirado dos documentos oficiais dos Pydantic: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "Informação" diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 625fa2b11..2b5f82464 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -34,7 +34,7 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Adicionar a tarefa em segundo plano @@ -42,7 +42,7 @@ E como a operação de gravação não usa `async` e `await`, definimos a funç Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` recebe como argumentos: @@ -58,7 +58,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md index 7137bf865..fcc30961f 100644 --- a/docs/pt/docs/tutorial/bigger-applications.md +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Operações de Rota* com `APIRouter` @@ -96,7 +96,7 @@ E então você o utiliza para declarar suas *operações de rota*. Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". @@ -124,7 +124,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ Sabemos que todas as *operações de rota* neste módulo têm o mesmo: Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` Como o caminho de cada *operação de rota* deve começar com `/`, como em: @@ -243,7 +243,7 @@ E precisamos obter a função de dependência do módulo `app.dependencies`, o a Então usamos uma importação relativa com `..` para as dependências: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### Como funcionam as importações relativas @@ -316,7 +316,7 @@ Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operaç Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip | "Dica" @@ -344,7 +344,7 @@ Você importa e cria uma classe `FastAPI` normalmente. E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Importe o `APIRouter` @@ -352,7 +352,7 @@ E podemos até declarar [dependências globais](dependencies/global-dependencies Agora importamos os outros submódulos que possuem `APIRouter`s: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". @@ -417,7 +417,7 @@ o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Incluir o `APIRouter`s para `usuários` e `itens` @@ -425,7 +425,7 @@ Então, para poder usar ambos no mesmo arquivo, importamos os submódulos direta Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info | "Informação" @@ -467,7 +467,7 @@ Ele contém um `APIRouter` com algumas *operações de rota* de administração Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. @@ -475,7 +475,7 @@ Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` p Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. @@ -498,7 +498,7 @@ Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastA Aqui fazemos isso... só para mostrar que podemos 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index cce37cd55..ab9377fdb 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -7,7 +7,7 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` /// warning | "Aviso" @@ -21,7 +21,7 @@ Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como Você pode então utilizar `Field` com atributos do modelo: ```Python hl_lines="11-14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index d36dd60b3..400813a7b 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v //// tab | Python 3.10+ ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -48,7 +48,7 @@ Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `i //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -56,7 +56,7 @@ Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `i //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -103,7 +103,7 @@ Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo u //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -111,7 +111,7 @@ Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo u //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ Por exemplo: //// tab | Python 3.10+ ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -165,7 +165,7 @@ Por exemplo: //// tab | Python 3.8+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -193,7 +193,7 @@ como em: //// tab | Python 3.10+ ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -201,7 +201,7 @@ como em: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 7d933b27f..3aa79d563 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -21,7 +21,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### Declare a `List` com um parâmetro de tipo @@ -45,7 +45,7 @@ Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente u ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## Tipo "set" @@ -59,7 +59,7 @@ Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -83,7 +83,7 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### Use o sub-modelo como um tipo @@ -91,7 +91,7 @@ Por exemplo, nós podemos definir um modelo `Image`: E então podemos usa-lo como o tipo de um atributo: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -126,7 +126,7 @@ Para ver todas as opções possíveis, cheque a documentação para os ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro importe `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Primeiro importe `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -68,7 +68,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -76,7 +76,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -84,7 +84,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -98,7 +98,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -112,7 +112,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index e5e2f8c27..16c4e9bf5 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -47,7 +47,7 @@ Você também pode especificar se o seu backend permite: * Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index 54582fcbc..6bac7eb85 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### Sobre `__name__ == "__main__"` diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 420503b87..179bfefb5 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4a7a29390..7d7086945 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ Ele deve ser uma lista de `Depends()`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Ele deve ser uma lista de `Depends()`: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ Dependências podem declarar requisitos de requisições (como cabeçalhos) ou o //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Dependências podem declarar requisitos de requisições (como cabeçalhos) ou o //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ Essas dependências podem levantar exceções, da mesma forma que dependências //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Essas dependências podem levantar exceções, da mesma forma que dependências //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -169,7 +169,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que Utilize a versão com `Annotated` se possível ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 16c2cf899..d90bebe39 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` O código após o `yield` é executado após a resposta ser entregue: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Dica" @@ -64,7 +64,7 @@ Então, você pode procurar por essa exceção específica dentro da dependênci Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções. ```python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Subdependências com `yield` @@ -78,7 +78,7 @@ Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` de //// tab | python 3.9+ ```python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` de //// tab | python 3.8+ ```python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada //// tab | python 3.9+ ```python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada //// tab | python 3.8+ ```python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ Mas ela existe para ser utilizada caso você precise. 🤓 //// tab | python 3.9+ ```python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ Mas ela existe para ser utilizada caso você precise. 🤓 //// tab | python 3.8+ ```python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -210,7 +210,7 @@ Se você capturar uma exceção com `except` em uma dependência que utilize `yi //// tab | Python 3.9+ ```Python hl_lines="15-16" -{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -218,7 +218,7 @@ Se você capturar uma exceção com `except` em uma dependência que utilize `yi //// tab | Python 3.8+ ```Python hl_lines="14-15" -{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +{!> ../../docs_src/dependencies/tutorial008c_an.py!} ``` //// @@ -232,7 +232,7 @@ utilize a versão com `Annotated` se possível. /// ```Python hl_lines="13-14" -{!> ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -248,7 +248,7 @@ Você pode relançar a mesma exceção utilizando `raise`: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} ``` //// @@ -256,7 +256,7 @@ Você pode relançar a mesma exceção utilizando `raise`: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -270,7 +270,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial008d.py!} +{!> ../../docs_src/dependencies/tutorial008d.py!} ``` //// @@ -403,7 +403,7 @@ Em python, você pode criar Gerenciadores de Contexto ao ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicaçã //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md index f7b32966c..2a63e7ab8 100644 --- a/docs/pt/docs/tutorial/dependencies/index.md +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md index 279bf3339..b890fe793 100644 --- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index c104098ee..c8ce77e74 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ A função recebe um objeto, como um modelo Pydantic e retorna uma versão compa //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ A função recebe um objeto, como um modelo Pydantic e retorna uma versão compa //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index 5d50d8942..78f7ac694 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -56,11 +56,11 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. ```Python hl_lines="1 3 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: ```Python hl_lines="18-19" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 564aeadca..03227f2bb 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos d //// tab | Python 3.8 and above ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos d //// tab | Python 3.10 and above ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -171,7 +171,7 @@ Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `passw //// tab | Python 3.8 and above ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -179,7 +179,7 @@ Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `passw //// tab | Python 3.10 and above ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -201,7 +201,7 @@ Ao definir um ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -209,7 +209,7 @@ Ao definir um ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -237,7 +237,7 @@ Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python //// tab | Python 3.8 and above ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -245,7 +245,7 @@ Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python //// tab | Python 3.9 and above ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -261,7 +261,7 @@ Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e //// tab | Python 3.8 and above ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// @@ -269,7 +269,7 @@ Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e //// tab | Python 3.9 and above ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 4c2a8a8e3..4990b5984 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ O arquivo FastAPI mais simples pode se parecer com: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copie o conteúdo para um arquivo `main.py`. @@ -134,7 +134,7 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. @@ -150,7 +150,7 @@ Você pode usar todas as funcionalidades do ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro importe `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Se por algum motivo você precisar desabilitar a conversão automática de subli //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ Se por algum motivo você precisar desabilitar a conversão automática de subli //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -109,7 +109,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -125,7 +125,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md index 1760246ee..35c61d5fc 100644 --- a/docs/pt/docs/tutorial/middleware.md +++ b/docs/pt/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ A função middleware recebe: * Você pode então modificar ainda mais o `response` antes de retorná-lo. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "Dica" @@ -60,7 +60,7 @@ E também depois que a `response` é gerada, antes de retorná-la. Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## Outros middlewares diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index c57813780..48753d725 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.8 and above ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.9 and above ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.10 and above ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -57,7 +57,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.8 and above ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -65,7 +65,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.9 and above ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.10 and above ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Resumo e descrição @@ -101,7 +101,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.8 and above ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -109,7 +109,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.9 and above ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.10 and above ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -131,7 +131,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -139,7 +139,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -164,7 +164,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.8 and above ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -172,7 +172,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.9 and above ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -180,7 +180,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.10 and above ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -206,7 +206,7 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 08ed03f75..28c55482f 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ Primeiro, importe `Path` de `fastapi`: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro, importe `Path` de `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -83,7 +83,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## Validações numéricas: maior que ou igual @@ -93,7 +93,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## Validações numéricas: maior que e menor que ou igual @@ -104,7 +104,7 @@ O mesmo se aplica para: * `le`: menor que ou igual (`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## Validações numéricas: valores do tipo float, maior que e menor que @@ -118,7 +118,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## Recapitulando diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index fb872e4f5..a68354a1b 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -19,7 +19,7 @@ Então, se você rodar este exemplo e for até expressão regular que combine com um padrão esperado pelo parâmetro: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -115,7 +115,7 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "Observação" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "Informação" @@ -165,7 +165,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` Então, com uma URL assim: @@ -202,7 +202,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` Se você for até: @@ -227,7 +227,7 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "Observação" @@ -255,13 +255,13 @@ Algumas delas não exibem todas as informações extras que declaramos, ainda qu Você pode adicionar um `title`: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` E uma `description`: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## Apelidos (alias) de parâmetros @@ -283,7 +283,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## Parâmetros descontinuados @@ -295,7 +295,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 78d54f09b..6e6699cd5 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -66,7 +66,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Você também pode declarar tipos `bool`, e eles serão convertidos: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Você também pode declarar tipos `bool`, e eles serão convertidos: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -150,7 +150,7 @@ Eles serão detectados pelo nome: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -158,7 +158,7 @@ Eles serão detectados pelo nome: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -220,7 +220,7 @@ E claro, você pode definir alguns parâmetros como obrigatórios, alguns possui //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -228,7 +228,7 @@ E claro, você pode definir alguns parâmetros como obrigatórios, alguns possui //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index a9db18e9d..837e24c34 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -27,7 +27,7 @@ Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja re //// tab | Python 3.9+ ```Python hl_lines="9-11 15" -{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} ``` //// @@ -35,7 +35,7 @@ Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja re //// tab | Python 3.8+ ```Python hl_lines="8-10 14" -{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +{!> ../../docs_src/request_form_models/tutorial001_an.py!} ``` //// @@ -49,7 +49,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7-9 13" -{!> ../../../docs_src/request_form_models/tutorial001.py!} +{!> ../../docs_src/request_form_models/tutorial001.py!} ``` //// @@ -79,7 +79,7 @@ Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualqu //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualqu //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +{!> ../../docs_src/request_form_models/tutorial002_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/request_form_models/tutorial002.py!} +{!> ../../docs_src/request_form_models/tutorial002.py!} ``` //// diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 2cf406386..29488b4f2 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ Por exemplo: `pip install python-multipart`. ## Importe `File` e `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## Defina parâmetros de `File` e `Form` @@ -21,7 +21,7 @@ Por exemplo: `pip install python-multipart`. Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index fc8c7bbad..1e2faf269 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ Ex: `pip install python-multipart`. Importe `Form` de `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## Declare parâmetros de `Form` @@ -23,7 +23,7 @@ Importe `Form` de `fastapi`: Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md index 60e4ecb26..39bfe284a 100644 --- a/docs/pt/docs/tutorial/request_files.md +++ b/docs/pt/docs/tutorial/request_files.md @@ -19,7 +19,7 @@ Importe `File` e `UploadFile` do `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Importe `File` e `UploadFile` do `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Fo //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Fo //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ Defina um parâmetro de arquivo com o tipo `UploadFile` //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Defina um parâmetro de arquivo com o tipo `UploadFile` //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ Utilize a versão com `Annotated`, se possível /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ Utilize a versão com `Annotated`, se possível /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ Para usar isso, declare uma lista de `bytes` ou `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ Para usar isso, declare uma lista de `bytes` ou `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ E da mesma forma que antes, você pode utilizar `File()` para definir parâmetro //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ E da mesma forma que antes, você pode utilizar `File()` para definir parâmetro //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index dc8e12048..bc4a2cd34 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * etc. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Nota" @@ -78,7 +78,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver Vamos ver o exemplo anterior novamente: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` é o código de status para "Criado". @@ -88,7 +88,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index a291db045..2d78e4ef1 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -9,7 +9,7 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: ```Python hl_lines="15-23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. @@ -29,7 +29,7 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: ```Python hl_lines="4 10-13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` /// warning | "Atenção" @@ -57,7 +57,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: ```Python hl_lines="21-26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ### Exemplo na UI da documentação @@ -80,7 +80,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. ```Python hl_lines="22-48" -{!../../../docs_src/schema_extra_example/tutorial004.py!} +{!../../docs_src/schema_extra_example/tutorial004.py!} ``` ### Exemplos na UI da documentação diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 007fefcb9..9fb94fe67 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -20,7 +20,7 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente Copie o exemplo em um arquivo `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## Execute-o @@ -136,7 +136,7 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip | "Dica" @@ -180,7 +180,7 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index efaf07dfb..901fca1d2 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * "Monte" uma instância de `StaticFiles()` em um caminho específico. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Detalhes técnicos" diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index f734a7d9a..4e28a43c0 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -31,7 +31,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`. Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Dica" @@ -79,7 +79,7 @@ No arquivo `main.py` você tem seu aplicativo **FastAPI**: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Arquivo de teste @@ -97,7 +97,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...e ter o código para os testes como antes. @@ -129,7 +129,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -137,7 +137,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -145,7 +145,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -159,7 +159,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -173,7 +173,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -183,7 +183,7 @@ Prefira usar a versão `Annotated` se possível. Você pode então atualizar `test_main.py` com os testes estendidos: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index c052bc675..e5905304a 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -23,7 +23,7 @@ Python имеет поддержку необязательных аннотац Давайте начнем с простого примера: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Вызов этой программы выводит: @@ -39,7 +39,7 @@ John Doe * Соединяет их через пробел. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Отредактируем пример @@ -83,7 +83,7 @@ John Doe Это аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Это не то же самое, что объявление значений по умолчанию, например: @@ -113,7 +113,7 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -123,7 +123,7 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Объявление типов @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типы с параметрами типов @@ -162,7 +162,7 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -172,7 +172,7 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip @@ -200,7 +200,7 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Это означает: @@ -217,7 +217,7 @@ John Doe Второй параметр типа предназначен для значений `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Это означает: @@ -231,7 +231,7 @@ John Doe Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`. @@ -256,13 +256,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Тогда вы можете объявить переменную типа `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` И снова вы получаете полную поддержку редактора: @@ -284,7 +284,7 @@ John Doe Взято из официальной документации Pydantic: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 073276848..0f6ce0eb3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -34,7 +34,7 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Добавление фоновой задачи @@ -42,7 +42,7 @@ Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` принимает следующие аргументы: @@ -60,7 +60,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.8+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index f4db0e9ff..f3b2c6113 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | Python 3.8+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 107e6293b..53965f0ec 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ q: str | None = None //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ q: str | None = None //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ q: str | None = None //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ q: str | None = None /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ q: str | None = None /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ item: Item = Body(embed=True) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ item: Item = Body(embed=True) //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ item: Item = Body(embed=True) //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index ecb8b92a7..780946725 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Объявление `list` с указанием типов для вложенных элементов @@ -68,7 +68,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ images: list[Image] //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ images: list[Image] //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ images: list[Image] //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ images: list[Image] //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index c458329d8..3ecfe52f4 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.6+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | Python 3.6+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -115,7 +115,7 @@ //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -123,7 +123,7 @@ //// tab | Python 3.6+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -146,7 +146,7 @@ //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -154,7 +154,7 @@ //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -162,7 +162,7 @@ //// tab | Python 3.6+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index c3e6326da..91b169d07 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -23,7 +23,7 @@ Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Создание вашей собственной модели @@ -33,7 +33,7 @@ Используйте аннотации типов Python для всех атрибутов: ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -63,7 +63,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -132,7 +132,7 @@ Внутри функции вам доступны все атрибуты объекта модели напрямую: ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Тело запроса + параметры пути @@ -142,7 +142,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Тело запроса + параметры пути + параметры запроса @@ -152,7 +152,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Параметры функции распознаются следующим образом: diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index e88b9d7ee..2a73a5918 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 852833208..8d415a2c1 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 685fb7356..606a32bfc 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### Описание `__name__ == "__main__"` diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index d0471baca..161101bb3 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.6+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -120,7 +120,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -128,7 +128,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -136,7 +136,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -150,7 +150,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -164,7 +164,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -174,7 +174,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -182,7 +182,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -190,7 +190,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -204,7 +204,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -218,7 +218,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -228,7 +228,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -236,7 +236,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -244,7 +244,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -258,7 +258,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -272,7 +272,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -294,7 +294,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -302,7 +302,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -310,7 +310,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -324,7 +324,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -338,7 +338,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -438,7 +438,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -446,7 +446,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -454,7 +454,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -468,7 +468,7 @@ commons = Depends(CommonQueryParams) /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -482,7 +482,7 @@ commons = Depends(CommonQueryParams) /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -575,7 +575,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -583,7 +583,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -591,7 +591,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -605,7 +605,7 @@ commons: CommonQueryParams = Depends() /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -619,7 +619,7 @@ commons: CommonQueryParams = Depends() /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 11df4b474..305ce46cb 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index ece7ef8e3..99a86e999 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI поддерживает зависимости, которые выпо Перед созданием ответа будет выполнен только код до и включая `yield`. ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Код, следующий за оператором `yield`, выполняется после доставки ответа: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Подсказка" @@ -64,7 +64,7 @@ FastAPI поддерживает зависимости, которые выпо Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Подзависимости с `yield` @@ -78,7 +78,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ FastAPI поддерживает зависимости, которые выпо /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ FastAPI поддерживает зависимости, которые выпо /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -304,7 +304,7 @@ with open("./somefile.txt") as f: `with` или `async with` внутри функции зависимости: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` /// tip | "Подсказка" diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index 9e03e3723..7dbd50ae1 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index b244b3fdc..fcd9f46dc 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -40,7 +40,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -48,7 +48,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -62,7 +62,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -114,7 +114,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -122,7 +122,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -130,7 +130,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -144,7 +144,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -158,7 +158,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -186,7 +186,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -200,7 +200,7 @@ /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -214,7 +214,7 @@ /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -273,7 +273,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -281,7 +281,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -289,7 +289,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 332470396..ae0fd0824 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ //// tab | Python 3.6+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.6+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ //// tab | Python 3.6+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index 02c3587f3..c9900cb2c 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.6+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 2650bb0af..82cb0ff7a 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.8 и выше ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.10 и выше ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.8 и выше ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10 и выше ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 2aac76aa3..e7ff3f40f 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -171,7 +171,7 @@ UserInDB( //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -179,7 +179,7 @@ UserInDB( //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -201,7 +201,7 @@ UserInDB( //// tab | Python 3.10+ ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -209,7 +209,7 @@ UserInDB( //// tab | Python 3.8+ ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -237,7 +237,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -245,7 +245,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -261,7 +261,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -269,7 +269,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index e60d58823..b1de217cd 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Самый простой FastAPI файл может выглядеть так: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Скопируйте в файл `main.py`. @@ -134,7 +134,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` это класс в Python, который предоставляет всю функциональность для API. @@ -150,7 +150,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 2: создайте экземпляр `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Переменная `app` является экземпляром класса `FastAPI`. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload Если создать такое приложение: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -251,7 +251,7 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: @@ -307,7 +307,7 @@ https://example.com/items/foo * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Это обычная Python функция. @@ -321,7 +321,7 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Технические детали" @@ -333,7 +333,7 @@ https://example.com/items/foo ### Шаг 5: верните результат ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index 028f3e0d2..e7bfb85aa 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### Импортируйте `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Вызовите `HTTPException` в своем коде @@ -42,7 +42,7 @@ В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Возвращаемый ответ @@ -82,7 +82,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## Установка пользовательских обработчиков исключений @@ -96,7 +96,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -136,7 +136,7 @@ Обработчик исключения получит объект `Request` и исключение. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -189,7 +189,7 @@ path -> item_id Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "Технические детали" @@ -207,7 +207,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` Теперь попробуйте отправить недействительный элемент, например: @@ -267,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 3b5e38328..18e1e60d0 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 9799fe538..246458f42 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -18,7 +18,7 @@ Вы можете задать их следующим образом: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip | "Подсказка" @@ -52,7 +52,7 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). @@ -67,7 +67,7 @@ Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info | "Дополнительная информация" @@ -97,7 +97,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -116,5 +116,5 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index 26b1726ad..5f3855af2 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Краткое и развёрнутое содержание @@ -101,7 +101,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ //// tab | Python 3.10+ ```Python hl_lines="17-25" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ OpenAPI указывает, что каждой *операции пути* не Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index ced12c826..bf42ec725 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -167,7 +167,7 @@ Path-параметр всегда является обязательным, п /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -177,7 +177,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -185,7 +185,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -214,7 +214,7 @@ Path-параметр всегда является обязательным, п Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Лучше с `Annotated` @@ -224,7 +224,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -232,7 +232,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -246,7 +246,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -254,7 +254,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -268,7 +268,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -283,7 +283,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -291,7 +291,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -305,7 +305,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -323,7 +323,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -331,7 +331,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -345,7 +345,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index dc3d64af4..d1d76cf7b 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -19,7 +19,7 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` Здесь, `item_id` объявлен типом `int`. @@ -123,7 +123,7 @@ ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. @@ -131,7 +131,7 @@ Аналогично, вы не можете переопределить операцию с путем: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` Первый будет выполняться всегда, так как путь совпадает первым. @@ -149,7 +149,7 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "Дополнительная информация" @@ -169,7 +169,7 @@ Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Проверьте документацию @@ -187,7 +187,7 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Получение *значения перечисления* @@ -195,7 +195,7 @@ Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "Подсказка" @@ -211,7 +211,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` Вы отправите клиенту такой JSON-ответ: @@ -251,7 +251,7 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "Подсказка" diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index e6653a837..0054af6ed 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ FastAPI определит параметр `q` как необязательн В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ FastAPI определит параметр `q` как необязательн Эта библиотека будет установлена вместе с FastAPI. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -116,7 +116,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -154,7 +154,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -268,7 +268,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -276,7 +276,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -298,7 +298,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -312,7 +312,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -324,7 +324,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -332,7 +332,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -340,7 +340,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -354,7 +354,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -368,7 +368,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -392,7 +392,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -400,7 +400,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -414,7 +414,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -462,7 +462,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -470,7 +470,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -484,7 +484,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip | "Подсказка" @@ -504,7 +504,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -512,7 +512,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -526,7 +526,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -550,7 +550,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -558,7 +558,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -566,7 +566,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -580,7 +580,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -594,7 +594,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -612,7 +612,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} ``` //// @@ -620,7 +620,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ ```Python hl_lines="2 9" -{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} ``` //// @@ -634,7 +634,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="2 8" -{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} ``` //// @@ -654,7 +654,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -662,7 +662,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -670,7 +670,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -684,7 +684,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -698,7 +698,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -712,7 +712,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -753,7 +753,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -761,7 +761,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -775,7 +775,7 @@ http://localhost:8000/items/?q=foo&q=bar /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -789,7 +789,7 @@ http://localhost:8000/items/?q=foo&q=bar /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -818,7 +818,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -826,7 +826,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -840,7 +840,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -872,7 +872,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -880,7 +880,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -888,7 +888,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -902,7 +902,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -916,7 +916,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -926,7 +926,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -934,7 +934,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -942,7 +942,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -956,7 +956,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -970,7 +970,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -996,7 +996,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -1004,7 +1004,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1012,7 +1012,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1026,7 +1026,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1040,7 +1040,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1056,7 +1056,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1064,7 +1064,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1072,7 +1072,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1086,7 +1086,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1100,7 +1100,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1116,7 +1116,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1124,7 +1124,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1132,7 +1132,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1146,7 +1146,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1160,7 +1160,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 061f9be04..edf06746b 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -66,7 +66,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -221,7 +221,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -229,7 +229,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 1fbc4acc0..34b9c94fa 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.6+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ //// tab | Python 3.6+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.6+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ contents = myfile.file.read() //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ contents = myfile.file.read() /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ contents = myfile.file.read() /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ contents = myfile.file.read() /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ contents = myfile.file.read() /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ contents = myfile.file.read() /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ contents = myfile.file.read() /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ contents = myfile.file.read() /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index b38962866..9b449bcd9 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -15,7 +15,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -23,7 +23,7 @@ //// tab | Python 3.6+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -37,7 +37,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -49,7 +49,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | Python 3.6+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -71,7 +71,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 3737f1347..93b44437b 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index f8c910fe9..363e64676 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -142,7 +142,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -150,7 +150,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -174,7 +174,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -182,7 +182,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -192,7 +192,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -210,7 +210,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -218,7 +218,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -248,7 +248,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -256,7 +256,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -302,7 +302,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -314,7 +314,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -328,7 +328,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} ``` //// @@ -336,7 +336,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -354,7 +354,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -362,7 +362,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -376,7 +376,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -384,7 +384,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -392,7 +392,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -412,7 +412,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -420,7 +420,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -428,7 +428,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -523,7 +523,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -551,7 +551,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -559,7 +559,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index a36c42d05..48808bea7 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * и других. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Примечание" @@ -77,7 +77,7 @@ FastAPI знает об этом и создаст документацию Open Рассмотрим предыдущий пример еще раз: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` – это код статуса "Создано". @@ -87,7 +87,7 @@ FastAPI знает об этом и создаст документацию Open Для удобства вы можете использовать переменные из `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index 1b216de3a..daa264afc 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13-21" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.8+ ```Python hl_lines="15-23" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.10+ ```Python hl_lines="22-27" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -91,7 +91,7 @@ //// tab | Python 3.9+ ```Python hl_lines="22-27" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -99,7 +99,7 @@ //// tab | Python 3.8+ ```Python hl_lines="23-28" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -113,7 +113,7 @@ /// ```Python hl_lines="18-23" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -127,7 +127,7 @@ /// ```Python hl_lines="20-25" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -154,7 +154,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -162,7 +162,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -184,7 +184,7 @@ /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -198,7 +198,7 @@ /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index 444a06915..c98ce2c60 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -155,7 +155,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -163,7 +163,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -177,7 +177,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -221,7 +221,7 @@ oauth2_scheme(some, parameters) //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -229,7 +229,7 @@ oauth2_scheme(some, parameters) //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -243,7 +243,7 @@ oauth2_scheme(some, parameters) /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index ccddae249..4734554f3 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Технические детали" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index efefbfb01..ae045bbbe 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -27,7 +27,7 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Подсказка" @@ -75,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Файл тестов @@ -93,7 +93,7 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...и писать дальше тесты, как и раньше. @@ -125,7 +125,7 @@ //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -133,7 +133,7 @@ //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -141,7 +141,7 @@ //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -155,7 +155,7 @@ /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -169,7 +169,7 @@ /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -179,7 +179,7 @@ Теперь обновим файл `test_main.py`, добавив в него тестов: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index 59a2499e2..aa8a040d0 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Not" diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md index 54a6f20e2..bc8da16df 100644 --- a/docs/tr/docs/advanced/wsgi.md +++ b/docs/tr/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. Son olarak da bir yol altında bağlama işlemini gerçekleştirin. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Kontrol Edelim diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index b8b880c6d..9584a5732 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -23,7 +23,7 @@ Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, Basit bir örnek ile başlayalım: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Programın çıktısı: @@ -39,7 +39,7 @@ Fonksiyon sırayla şunları yapar: * Değişkenleri aralarında bir boşlukla beraber Birleştirir. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Düzenle @@ -83,7 +83,7 @@ Bu kadar. İşte bunlar "tip belirteçleri": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -113,7 +113,7 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -123,7 +123,7 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Tip bildirme @@ -144,7 +144,7 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tip parametreleri ile Generic tipler @@ -162,7 +162,7 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -172,7 +172,7 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Ipucu" @@ -200,7 +200,7 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Bu şu anlama geliyor: @@ -217,7 +217,7 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Bu şu anlama gelir: @@ -231,7 +231,7 @@ Bu şu anlama gelir: `Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur. @@ -256,13 +256,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Ve yine bütün editör desteğini alırsınız: @@ -284,7 +284,7 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 807f85e8a..895cf9b03 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index 76c035992..335fcaece 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ En sade FastAPI dosyası şu şekilde görünür: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. @@ -134,7 +134,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 1: `FastAPI`yı Projemize Dahil Edelim ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. @@ -150,7 +150,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -251,7 +251,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. #### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: @@ -307,7 +307,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bu bir Python fonksiyonudur. @@ -321,7 +321,7 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur. Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Not" @@ -333,7 +333,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr ### Adım 5: İçeriği Geri Döndürün ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index d36242083..9017d99ab 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. @@ -19,7 +19,7 @@ Eğer bu örneği çalıştırıp ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanı //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanı //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -223,7 +223,7 @@ Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve b //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -231,7 +231,7 @@ Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve b //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 8e8ccfba4..19b6150ff 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ Formları kullanmak için öncelikle ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Formları kullanmak için öncelikle ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index b82be611f..8bff59744 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * Bir `StaticFiles()` örneğini belirli bir yola bağlayın. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Teknik Detaylar" diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 511a5264a..573b5372c 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -23,7 +23,7 @@ Python підтримує додаткові "підказки типу" ("type Давайте почнемо з простого прикладу: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Виклик цієї програми виводить: @@ -39,7 +39,7 @@ John Doe * Конкатенує їх разом із пробілом по середині. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Редагуйте це @@ -83,7 +83,7 @@ John Doe Це "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -113,7 +113,7 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -123,7 +123,7 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Оголошення типів @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типи з параметрами типів @@ -172,7 +172,7 @@ John Doe З модуля `typing`, імпортуємо `List` (з великої літери `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). @@ -182,7 +182,7 @@ John Doe Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -196,7 +196,7 @@ John Doe Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -234,7 +234,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -242,7 +242,7 @@ John Doe //// tab | Python 3.9 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -263,7 +263,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -271,7 +271,7 @@ John Doe //// tab | Python 3.9 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -293,7 +293,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -301,7 +301,7 @@ John Doe //// tab | Python 3.10 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -315,7 +315,7 @@ John Doe У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`. @@ -327,7 +327,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -335,7 +335,7 @@ John Doe //// tab | Python 3.8 і вище - альтернатива ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -343,7 +343,7 @@ John Doe //// tab | Python 3.10 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -407,13 +407,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Потім ви можете оголосити змінну типу `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` І знову ж таки, ви отримуєте всю підтримку редактора: @@ -437,7 +437,7 @@ John Doe //// tab | Python 3.8 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -445,7 +445,7 @@ John Doe //// tab | Python 3.9 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -453,7 +453,7 @@ John Doe //// tab | Python 3.10 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index e4d5b1fad..b1f645932 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 50fd76f84..1e4188831 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 4720a42ba..40ca4f6e6 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 9ef8d5c5d..39dca9be8 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 54cbd4b00..5e6c364e4 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 784da65f5..6f79c0d1d 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Найпростіший файл FastAPI може виглядати так: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Скопіюйте це до файлу `main.py`. @@ -158,7 +158,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 1: імпортуємо `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` це клас у Python, який надає всю функціональність для API. @@ -174,7 +174,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 2: створюємо екземпляр `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Змінна `app` є екземпляром класу `FastAPI`. @@ -243,7 +243,7 @@ https://example.com/items/foo #### Визначте декоратор операції шляху (path operation decorator) ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: @@ -298,7 +298,7 @@ https://example.com/items/foo * **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Це звичайна функція Python. @@ -312,7 +312,7 @@ FastAPI викликатиме її щоразу, коли отримає зап Ви також можете визначити її як звичайну функцію замість `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Примітка" @@ -324,7 +324,7 @@ FastAPI викликатиме її щоразу, коли отримає зап ### Крок 5: поверніть результат ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 99d1d207f..275b0eb39 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -23,7 +23,7 @@ Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ Hãy bắt đầu với một ví dụ đơn giản: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Kết quả khi gọi chương trình này: @@ -39,7 +39,7 @@ Hàm thực hiện như sau: * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Sửa đổi @@ -83,7 +83,7 @@ Chính là nó. Những thứ đó là "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Đó không giống như khai báo những giá trị mặc định giống như: @@ -113,7 +113,7 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -123,7 +123,7 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Khai báo các kiểu dữ liệu @@ -144,7 +144,7 @@ Bạn có thể sử dụng, ví dụ: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -182,7 +182,7 @@ Tương tự kiểu dữ liệu `list`. Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệ Từ `typing`, import `List` (với chữ cái `L` viết hoa): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Khai báo biến với cùng dấu hai chấm (`:`). @@ -202,7 +202,7 @@ Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -302,7 +302,7 @@ Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -310,7 +310,7 @@ Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -324,7 +324,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`. @@ -336,7 +336,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -344,7 +344,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -352,7 +352,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -375,7 +375,7 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -393,7 +393,7 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -458,13 +458,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sau đó bạn có thể khai báo một biến có kiểu là `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: @@ -492,7 +492,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -500,7 +500,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -508,7 +508,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -538,7 +538,7 @@ Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -550,7 +550,7 @@ Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đ Nó đã được cài đặt sẵng cùng với **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index ce808eb91..d80d78506 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Sao chép sang một tệp tin `main.py`. @@ -134,7 +134,7 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c ### Bước 1: import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. @@ -150,7 +150,7 @@ Bạn cũng có thể sử dụng tất cả `dataclasses`): ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -35,7 +35,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 在 `response_model` 参数中使用 `dataclasses`: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` 本例把数据类自动转换为 Pydantic 数据类。 @@ -53,7 +53,7 @@ API 文档中也会显示相关概图: 本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. 本例依然要从标准的 `dataclasses` 中导入 `field`; diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index c9389f533..e5b44f321 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -15,7 +15,7 @@ 使用 `startup` 事件声明 `app` 启动前运行的函数: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -29,7 +29,7 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index 56aad3bd2..baf131361 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -138,7 +138,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -146,7 +146,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -199,7 +199,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -207,7 +207,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -233,7 +233,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: ```Python -{!../../../docs_src/generate_clients/tutorial004.py!} +{!../../docs_src/generate_clients/tutorial004.py!} ``` 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 926082b94..525dc89ac 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -58,7 +58,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` 支持以下参数: @@ -82,7 +82,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` 支持以下参数: diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index 7c7323cb5..dc1c2539b 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: ```Python hl_lines="10-14 37-54" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "提示" @@ -93,7 +93,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 首先,新建包含一些用于回调的 `APIRouter`。 ```Python hl_lines="5 26" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### 创建回调*路径操作* @@ -106,7 +106,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` ```Python hl_lines="17-19 22-23 29-33" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -176,7 +176,7 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): ```Python hl_lines="36" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index c37846916..0d77dd69e 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ 务必确保每个操作路径的 `operation_id` 都是唯一的。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### 使用 *路径操作函数* 的函数名作为 operationId @@ -23,7 +23,7 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstring 的高级描述 @@ -58,5 +58,5 @@ ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index a289cf201..c38f80f1f 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index dd942a981..5772664b0 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -5,7 +5,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -25,7 +25,7 @@ 然后设置Cookies,并返回: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index b2c7de8fd..9d191c622 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -36,7 +36,7 @@ ```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "技术细节" @@ -58,7 +58,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index e18d1620d..d593fdccc 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -6,7 +6,7 @@ 然后你可以在这个*临时*响应对象中设置头部。 ```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} +{!../../docs_src/response_headers/tutorial002.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -21,7 +21,7 @@ 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: ```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} +{!../../docs_src/response_headers/tutorial001.py!} ``` diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index a76353186..06c6dbbab 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -23,7 +23,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.9+ ```Python hl_lines="4 8 12" -{!> ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index b75ae11a4..d6354230e 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -63,7 +63,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 下面,我们逐步说明修改的代码内容。 @@ -75,7 +75,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: ```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -103,7 +103,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// ```Python hl_lines="153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 在*路径操作*与依赖项中声明作用域 @@ -131,7 +131,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// ```Python hl_lines="4 139 166" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` /// info | "技术细节" @@ -159,7 +159,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 ```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 使用 `scopes` @@ -175,7 +175,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 ```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `username` 与数据形状 @@ -193,7 +193,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 ```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `scopes` @@ -203,7 +203,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 ```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 依赖项树与作用域 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 37a2d98d3..4d35731cb 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -151,7 +151,7 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 ```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` /// tip @@ -169,7 +169,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### 运行服务器 @@ -205,13 +205,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` 然后在一个名为 `main.py` 的文件中使用它: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -231,7 +231,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -243,7 +243,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -251,7 +251,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -265,7 +265,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -283,7 +283,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -291,7 +291,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -305,7 +305,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -315,7 +315,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -358,7 +358,7 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: ```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} +{!../../docs_src/settings/app03/config.py!} ``` 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 @@ -395,7 +395,7 @@ def get_settings(): //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -403,7 +403,7 @@ def get_settings(): //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -417,7 +417,7 @@ def get_settings(): /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index a26301b50..f93ab1d24 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 子应用 @@ -21,7 +21,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 挂载子应用 @@ -31,7 +31,7 @@ 本例的子应用挂载在 `/subapi` 路径下: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 查看文档 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index b09644e39..1159302a9 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, ```Python hl_lines="4 11 15-16" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note | "笔记" @@ -57,7 +57,7 @@ $ pip install jinja2 编写模板 `templates/item.html`,代码如下: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### 模板上下文 @@ -111,13 +111,13 @@ Item ID: 42 你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` 本例中,它将链接到 `static/styles.css`中的CSS文件: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` 因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md index 58bf9af8c..ecab4f65b 100644 --- a/docs/zh/docs/advanced/testing-database.md +++ b/docs/zh/docs/advanced/testing-database.md @@ -49,7 +49,7 @@ 但其余的会话代码基本上都是一样的,只要复制就可以了。 ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip | "提示" @@ -73,7 +73,7 @@ Base.metadata.create_all(bind=engine) 因此,要在测试代码中添加这行代码创建新的数据库文件。 ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## 覆盖依赖项 @@ -81,7 +81,7 @@ Base.metadata.create_all(bind=engine) 接下来,创建覆盖依赖项,并为应用添加覆盖内容。 ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip | "提示" @@ -95,7 +95,7 @@ Base.metadata.create_all(bind=engine) 然后,就可以正常测试了。 ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` 测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index cc9a38200..c3d912e2f 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -29,7 +29,7 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 ```Python hl_lines="26-27 30" -{!../../../docs_src/dependency_testing/tutorial001.py!} +{!../../docs_src/dependency_testing/tutorial001.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 222a67c8c..00e661cd2 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index 795b73945..a69053f24 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "笔记" diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index bc9e898d9..992458217 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ 此时,需要直接访问请求。 ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index 3fcc36dfe..15ae84c58 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -35,7 +35,7 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## 创建 `websocket` @@ -43,7 +43,7 @@ $ pip install websockets 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "技术细节" @@ -59,7 +59,7 @@ $ pip install websockets 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` 您可以接收和发送二进制、文本和 JSON 数据。 @@ -112,7 +112,7 @@ $ uvicorn main:app --reload //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ $ uvicorn main:app --reload //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ $ uvicorn main:app --reload //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -142,7 +142,7 @@ $ uvicorn main:app --reload /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -156,7 +156,7 @@ $ uvicorn main:app --reload /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -203,7 +203,7 @@ $ uvicorn main:app --reload //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -211,7 +211,7 @@ $ uvicorn main:app --reload //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index 179ec88aa..92bd998d0 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ 之后将其挂载到某一个路径下。 ```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## 检查 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index 17f89b22f..1a2daeec1 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...在此之后,Swagger UI 将不会高亮代码: @@ -31,7 +31,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` 这个配置会改变语法高亮主题: @@ -45,7 +45,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 其包括这些默认配置参数: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` 你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 @@ -53,7 +53,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## 其他 Swagger UI 参数 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index c78852539..dab6bd4c0 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -23,7 +23,7 @@ 让我们从一个简单的例子开始: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 运行这段程序将输出: @@ -39,7 +39,7 @@ John Doe * 中间用一个空格来拼接它们。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 修改示例 @@ -83,7 +83,7 @@ John Doe 这些就是"类型提示": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 这和声明默认值是不同的,例如: @@ -113,7 +113,7 @@ John Doe 下面是一个已经有类型提示的函数: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -123,7 +123,7 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 声明类型 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 嵌套类型 @@ -162,7 +162,7 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同样以冒号(`:`)来声明这个变量。 @@ -172,7 +172,7 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -192,7 +192,7 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 这表示: @@ -209,7 +209,7 @@ John Doe 第二个子类型声明 `dict` 的所有值: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 这表示: @@ -225,13 +225,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 接下来,你可以将一个变量声明为 `Person` 类型: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 然后,你将再次获得所有的编辑器支持: @@ -253,7 +253,7 @@ John Doe 下面的例子来自 Pydantic 官方文档: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` /// info diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 95fd7b6b5..fc9312bc5 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -34,7 +34,7 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 添加后台任务 @@ -42,7 +42,7 @@ 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 接收以下参数: @@ -60,7 +60,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.9+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14 16 23 26" -{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index a0c7095e9..64afd99af 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ from app.routers import items 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### 使用 `APIRouter` 的*路径操作* @@ -96,7 +96,7 @@ from app.routers import items 使用方式与 `FastAPI` 类相同: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。 @@ -122,7 +122,7 @@ from app.routers import items 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` /// tip @@ -156,7 +156,7 @@ from app.routers import items 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` 由于每个*路径操作*的路径都必须以 `/` 开头,例如: @@ -217,7 +217,7 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### 相对导入如何工作 @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -318,7 +318,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 导入 `APIRouter` @@ -326,7 +326,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。 @@ -391,7 +391,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 包含 `users` 和 `items` 的 `APIRouter` @@ -399,7 +399,7 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -441,7 +441,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` 但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。 @@ -449,7 +449,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。 @@ -472,7 +472,7 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 6e4c385dd..ac59d7e6a 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index fe951e544..c3bc0db9e 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -140,7 +140,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -148,7 +148,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -156,7 +156,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -170,7 +170,7 @@ /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -184,7 +184,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -225,7 +225,7 @@ q: str = None //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -233,7 +233,7 @@ q: str = None //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -241,7 +241,7 @@ q: str = None //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -255,7 +255,7 @@ q: str = None /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -269,7 +269,7 @@ q: str = None /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -297,7 +297,7 @@ item: Item = Body(embed=True) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -305,7 +305,7 @@ item: Item = Body(embed=True) //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -313,7 +313,7 @@ item: Item = Body(embed=True) //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -327,7 +327,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -341,7 +341,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 26837abc6..316ba9878 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 声明具有子类型的 List @@ -58,7 +58,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -66,7 +66,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -74,7 +74,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -90,7 +90,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -98,7 +98,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -106,7 +106,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -134,7 +134,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -142,7 +142,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -150,7 +150,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -162,7 +162,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -170,7 +170,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -178,7 +178,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -217,7 +217,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -225,7 +225,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -233,7 +233,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -247,7 +247,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -255,7 +255,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -263,7 +263,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -307,7 +307,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -315,7 +315,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -323,7 +323,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -347,7 +347,7 @@ images: List[Image] //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -355,7 +355,7 @@ images: List[Image] //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -391,7 +391,7 @@ images: List[Image] //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -399,7 +399,7 @@ images: List[Image] //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 6c74d12e0..5e9008d6a 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 ```Python hl_lines="30-35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` `PUT` 用于接收替换现有数据的数据。 @@ -57,7 +57,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 使用 Pydantic 的 `update` 参数 @@ -67,7 +67,7 @@ 例如,`stored_item_model.copy(update=update_data)`: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 更新部分数据小结 @@ -86,7 +86,7 @@ * 返回更新后的模型。 ```Python hl_lines="30-37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index c47abec77..67a7f28e0 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -25,7 +25,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 7ca77696e..b01c28238 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -98,7 +98,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -112,7 +112,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index de880f347..1166d5c97 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 945094207..a5afa1aaa 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 关于 `__name__ == "__main__"` diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 9932f90fc..917459d1d 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -86,7 +86,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -94,7 +94,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.8+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -104,7 +104,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -112,7 +112,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -122,7 +122,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -130,7 +130,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -152,7 +152,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -160,7 +160,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -206,7 +206,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -254,7 +254,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -262,7 +262,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e6bbd47c1..c7cfe0531 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ 该参数的值是由 `Depends()` 组成的 `list`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 @@ -47,7 +47,7 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 触发异常 @@ -55,7 +55,7 @@ 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 返回值 @@ -65,7 +65,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 6058f7878..a30313719 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -99,7 +99,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -121,7 +121,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -173,7 +173,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -195,7 +195,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -217,7 +217,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -247,7 +247,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -269,7 +269,7 @@ FastAPI支持在完成后执行一些 Date: Mon, 7 Oct 2024 20:11:42 +0000 Subject: [PATCH 332/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 490f99c70..26cba035b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). From 797cad7162592b6e581228bec09682da8feb6752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 7 Oct 2024 22:18:07 +0200 Subject: [PATCH 333/356] =?UTF-8?q?=F0=9F=93=9D=20Fix=20extra=20mdx-base-p?= =?UTF-8?q?ath=20paths=20(#12397)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/sql-databases.md | 48 ++++++++++---------- docs/it/docs/index.md | 3 -- docs/pt/docs/tutorial/cookie-param-models.md | 16 +++---- scripts/docs.py | 2 +- 4 files changed, 33 insertions(+), 36 deletions(-) diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index f65fa773c..7836efae1 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -296,7 +296,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.10+ ```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -304,7 +304,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.9+ ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -312,7 +312,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.8+ ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -346,7 +346,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.10+ ```Python hl_lines="13-15 29-32" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -354,7 +354,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.9+ ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -362,7 +362,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.8+ ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -384,7 +384,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.10+ ```Python hl_lines="13 17-18 29 34-35" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -392,7 +392,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.9+ ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -400,7 +400,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.8+ ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -559,7 +559,7 @@ In a very simplistic way create the database tables: //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -567,7 +567,7 @@ In a very simplistic way create the database tables: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -597,7 +597,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in //// tab | Python 3.9+ ```Python hl_lines="13-18" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -605,7 +605,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in //// tab | Python 3.8+ ```Python hl_lines="15-20" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -629,7 +629,7 @@ This will then give us better editor support inside the *path operation function //// tab | Python 3.9+ ```Python hl_lines="22 30 36 45 51" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -637,7 +637,7 @@ This will then give us better editor support inside the *path operation function //// tab | Python 3.8+ ```Python hl_lines="24 32 38 47 53" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -657,7 +657,7 @@ Now, finally, here's the standard **FastAPI** *path operations* code. //// tab | Python 3.9+ ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -665,7 +665,7 @@ Now, finally, here's the standard **FastAPI** *path operations* code. //// tab | Python 3.8+ ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -766,7 +766,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -774,7 +774,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -782,7 +782,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -798,7 +798,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -806,7 +806,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -863,7 +863,7 @@ The middleware we'll add (just a function) will create a new SQLAlchemy `Session //// tab | Python 3.9+ ```Python hl_lines="12-20" -{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` //// @@ -871,7 +871,7 @@ The middleware we'll add (just a function) will create a new SQLAlchemy `Session //// tab | Python 3.8+ ```Python hl_lines="14-22" -{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} ``` //// diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 57940f0ed..3bfff82f1 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -1,6 +1,3 @@ -{!../../../docs/missing-translation.md!} - -

FastAPI

diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md index 12d7ee08c..671e0d74f 100644 --- a/docs/pt/docs/tutorial/cookie-param-models.md +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -23,7 +23,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.10+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} ``` //// @@ -31,7 +31,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.9+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} ``` //// @@ -39,7 +39,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.8+ ```Python hl_lines="10-13 17" -{!> ../../../docs_src/cookie_param_models/tutorial001_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} ``` //// @@ -53,7 +53,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7-10 14" -{!> ../../../docs_src/cookie_param_models/tutorial001_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} ``` //// @@ -67,7 +67,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001.py!} +{!> ../../docs_src/cookie_param_models/tutorial001.py!} ``` //// @@ -105,7 +105,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} ``` //// @@ -113,7 +113,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../../docs_src/cookie_param_models/tutorial002_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} ``` //// @@ -127,7 +127,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002.py!} +{!> ../../docs_src/cookie_param_models/tutorial002.py!} ``` //// diff --git a/scripts/docs.py b/scripts/docs.py index f0c51f7a6..e5c423d58 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -23,7 +23,7 @@ app = typer.Typer() mkdocs_name = "mkdocs.yml" missing_translation_snippet = """ -{!../../../docs/missing-translation.md!} +{!../../docs/missing-translation.md!} """ non_translated_sections = [ From ecc4133907df47830bab6f11607c981ec82091b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 7 Oct 2024 20:18:29 +0000 Subject: [PATCH 334/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 26cba035b..ab23184a1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). From 95f167f0480f8df94c06c95cd19323534d123a2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 7 Oct 2024 22:24:40 +0200 Subject: [PATCH 335/356] =?UTF-8?q?=E2=9E=95=20Add=20docs=20dependency:=20?= =?UTF-8?q?markdown-include-variants=20(#12399)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 1 + requirements-docs.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index a18af2022..e55c6f176 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -305,6 +305,7 @@ markdown_extensions: # Other extensions mdx_include: + markdown_include_variants: extra: analytics: diff --git a/requirements-docs.txt b/requirements-docs.txt index 16b2998b9..c05bd51e3 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -16,3 +16,4 @@ griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 +markdown-include-variants==0.0.1 From 6345147c245248302e90f0eb6371f7ab7557fd1b Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 7 Oct 2024 20:25:03 +0000 Subject: [PATCH 336/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ab23184a1..b9dfe3da5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). From 018e303fd9d04fe91a12cd39561d5bc5ca7b0aee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 10:37:32 +0200 Subject: [PATCH 337/356] =?UTF-8?q?=F0=9F=94=A7=20Add=20speakeasy-api=20to?= =?UTF-8?q?=20`sponsors=5Fbadge.yml`=20(#12404)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors_badge.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index d8a41fbcb..d45028aaa 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -30,3 +30,4 @@ logins: - svix - zuplo-oss - Kong + - speakeasy-api From fcb15b4db162f2504d3f9f984d938e9a8ff03b35 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 08:38:00 +0000 Subject: [PATCH 338/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b9dfe3da5..d785805e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). From 40490abaa3526eee394eb84362bfa4ca6b4da9d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 12:55:26 +0200 Subject: [PATCH 339/356] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20type=20an?= =?UTF-8?q?notations=20for=20improved=20`python-multipart`=20(#12407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 6 +++--- requirements-docs-tests.txt | 2 ++ requirements-tests.txt | 1 - 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 5cebbf00f..813c74620 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -91,14 +91,14 @@ multipart_incorrect_install_error = ( def ensure_multipart_is_installed() -> None: try: # __version__ is available in both multiparts, and can be mocked - from multipart import __version__ # type: ignore + from multipart import __version__ assert __version__ try: # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header # type: ignore + from multipart.multipart import parse_options_header - assert parse_options_header + assert parse_options_header # type: ignore[truthy-function] except ImportError: logger.error(multipart_incorrect_install_error) raise RuntimeError(multipart_incorrect_install_error) from None diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index b82df4933..40b956e51 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,2 +1,4 @@ # For mkdocstrings and tests httpx >=0.23.0,<0.25.0 +# For linting and generating docs versions +ruff ==0.6.4 diff --git a/requirements-tests.txt b/requirements-tests.txt index 2f2576dd5..7b1f7ea1a 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,6 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.6.4 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel From a94d61b2c09c7ba5bc2bf5016e590e2b0a35189e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 10:55:50 +0000 Subject: [PATCH 340/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d785805e9..16faa52f9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol). From c6dfdb85239d32eb0f9825b1374f780b33eb8a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 13:01:17 +0200 Subject: [PATCH 341/356] =?UTF-8?q?=F0=9F=94=A8=20Add=20script=20to=20gene?= =?UTF-8?q?rate=20variants=20of=20files=20(#12405)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/docs.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/scripts/docs.py b/scripts/docs.py index e5c423d58..f26f96d85 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -15,6 +15,7 @@ import mkdocs.utils import typer import yaml from jinja2 import Template +from ruff.__main__ import find_ruff_bin logging.basicConfig(level=logging.INFO) @@ -382,5 +383,41 @@ def langs_json(): print(json.dumps(langs)) +@app.command() +def generate_docs_src_versions_for_file(file_path: Path) -> None: + target_versions = ["py39", "py310"] + base_content = file_path.read_text(encoding="utf-8") + previous_content = {base_content} + for target_version in target_versions: + version_result = subprocess.run( + [ + find_ruff_bin(), + "check", + "--target-version", + target_version, + "--fix", + "--unsafe-fixes", + "-", + ], + input=base_content.encode("utf-8"), + capture_output=True, + ) + content_target = version_result.stdout.decode("utf-8") + format_result = subprocess.run( + [find_ruff_bin(), "format", "-"], + input=content_target.encode("utf-8"), + capture_output=True, + ) + content_format = format_result.stdout.decode("utf-8") + if content_format in previous_content: + continue + previous_content.add(content_format) + version_file = file_path.with_name( + file_path.name.replace(".py", f"_{target_version}.py") + ) + logging.info(f"Writing to {version_file}") + version_file.write_text(content_format, encoding="utf-8") + + if __name__ == "__main__": app() From 13a18f80b3b0c7f0272c67b6ac7b73aafbb8584c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 11:01:43 +0000 Subject: [PATCH 342/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 16faa52f9..e34fd0df9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -39,6 +39,7 @@ hide: ### Internal +* 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). From 7daaac2bc350e2907554a01eb7eb1286247e5832 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 9 Oct 2024 21:44:42 +0200 Subject: [PATCH 343/356] =?UTF-8?q?=E2=9C=A8=20Add=20new=20tutorial=20for?= =?UTF-8?q?=20SQL=20databases=20with=20SQLModel=20(#12285)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/advanced/testing-database.md | 101 -- docs/em/docs/how-to/sql-databases-peewee.md | 576 ------------ docs/en/docs/advanced/testing-database.md | 111 --- .../docs/how-to/async-sql-encode-databases.md | 201 ---- .../docs/how-to/nosql-databases-couchbase.md | 178 ---- docs/en/docs/how-to/sql-databases-peewee.md | 594 ------------ docs/en/docs/how-to/testing-database.md | 7 + .../img/tutorial/sql-databases/image01.png | Bin 78949 -> 69755 bytes .../img/tutorial/sql-databases/image02.png | Bin 83482 -> 69197 bytes docs/en/docs/tutorial/sql-databases.md | 888 ++++-------------- docs/en/mkdocs.yml | 9 +- docs/zh/docs/advanced/testing-database.md | 101 -- docs_src/async_sql_databases/tutorial001.py | 65 -- docs_src/nosql_databases/tutorial001.py | 53 -- docs_src/sql_databases/sql_app/__init__.py | 0 docs_src/sql_databases/sql_app/alt_main.py | 62 -- docs_src/sql_databases/sql_app/crud.py | 36 - docs_src/sql_databases/sql_app/database.py | 13 - docs_src/sql_databases/sql_app/main.py | 55 -- docs_src/sql_databases/sql_app/models.py | 26 - docs_src/sql_databases/sql_app/schemas.py | 37 - .../sql_databases/sql_app/tests/__init__.py | 0 .../sql_app/tests/test_sql_app.py | 50 - .../sql_databases/sql_app_py310/__init__.py | 0 .../sql_databases/sql_app_py310/alt_main.py | 60 -- docs_src/sql_databases/sql_app_py310/crud.py | 36 - .../sql_databases/sql_app_py310/database.py | 13 - docs_src/sql_databases/sql_app_py310/main.py | 53 -- .../sql_databases/sql_app_py310/models.py | 26 - .../sql_databases/sql_app_py310/schemas.py | 35 - .../sql_app_py310/tests/__init__.py | 0 .../sql_app_py310/tests/test_sql_app.py | 47 - .../sql_databases/sql_app_py39/__init__.py | 0 .../sql_databases/sql_app_py39/alt_main.py | 60 -- docs_src/sql_databases/sql_app_py39/crud.py | 36 - .../sql_databases/sql_app_py39/database.py | 13 - docs_src/sql_databases/sql_app_py39/main.py | 53 -- docs_src/sql_databases/sql_app_py39/models.py | 26 - .../sql_databases/sql_app_py39/schemas.py | 37 - .../sql_app_py39/tests/__init__.py | 0 .../sql_app_py39/tests/test_sql_app.py | 47 - docs_src/sql_databases/tutorial001.py | 71 ++ docs_src/sql_databases/tutorial001_an.py | 74 ++ .../sql_databases/tutorial001_an_py310.py | 73 ++ docs_src/sql_databases/tutorial001_an_py39.py | 73 ++ docs_src/sql_databases/tutorial001_py310.py | 69 ++ docs_src/sql_databases/tutorial001_py39.py | 71 ++ docs_src/sql_databases/tutorial002.py | 104 ++ docs_src/sql_databases/tutorial002_an.py | 104 ++ .../sql_databases/tutorial002_an_py310.py | 103 ++ docs_src/sql_databases/tutorial002_an_py39.py | 103 ++ docs_src/sql_databases/tutorial002_py310.py | 102 ++ docs_src/sql_databases/tutorial002_py39.py | 104 ++ requirements-docs.txt | 2 +- requirements-tests.txt | 5 +- scripts/playwright/sql_databases/image01.py | 37 + scripts/playwright/sql_databases/image02.py | 37 + .../test_async_sql_databases/__init__.py | 0 .../test_tutorial001.py | 146 --- .../test_sql_databases/test_sql_databases.py | 419 --------- .../test_sql_databases_middleware.py | 421 --------- .../test_sql_databases_middleware_py310.py | 433 --------- .../test_sql_databases_middleware_py39.py | 433 --------- .../test_sql_databases_py310.py | 432 --------- .../test_sql_databases_py39.py | 432 --------- .../test_testing_databases.py | 27 - .../test_testing_databases_py310.py | 28 - .../test_testing_databases_py39.py | 28 - .../test_sql_databases/test_tutorial001.py | 373 ++++++++ .../test_sql_databases/test_tutorial002.py | 481 ++++++++++ 70 files changed, 2154 insertions(+), 6336 deletions(-) delete mode 100644 docs/em/docs/advanced/testing-database.md delete mode 100644 docs/em/docs/how-to/sql-databases-peewee.md delete mode 100644 docs/en/docs/advanced/testing-database.md delete mode 100644 docs/en/docs/how-to/async-sql-encode-databases.md delete mode 100644 docs/en/docs/how-to/nosql-databases-couchbase.md delete mode 100644 docs/en/docs/how-to/sql-databases-peewee.md create mode 100644 docs/en/docs/how-to/testing-database.md delete mode 100644 docs/zh/docs/advanced/testing-database.md delete mode 100644 docs_src/async_sql_databases/tutorial001.py delete mode 100644 docs_src/nosql_databases/tutorial001.py delete mode 100644 docs_src/sql_databases/sql_app/__init__.py delete mode 100644 docs_src/sql_databases/sql_app/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app/crud.py delete mode 100644 docs_src/sql_databases/sql_app/database.py delete mode 100644 docs_src/sql_databases/sql_app/main.py delete mode 100644 docs_src/sql_databases/sql_app/models.py delete mode 100644 docs_src/sql_databases/sql_app/schemas.py delete mode 100644 docs_src/sql_databases/sql_app/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app/tests/test_sql_app.py delete mode 100644 docs_src/sql_databases/sql_app_py310/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py310/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app_py310/crud.py delete mode 100644 docs_src/sql_databases/sql_app_py310/database.py delete mode 100644 docs_src/sql_databases/sql_app_py310/main.py delete mode 100644 docs_src/sql_databases/sql_app_py310/models.py delete mode 100644 docs_src/sql_databases/sql_app_py310/schemas.py delete mode 100644 docs_src/sql_databases/sql_app_py310/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py delete mode 100644 docs_src/sql_databases/sql_app_py39/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py39/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app_py39/crud.py delete mode 100644 docs_src/sql_databases/sql_app_py39/database.py delete mode 100644 docs_src/sql_databases/sql_app_py39/main.py delete mode 100644 docs_src/sql_databases/sql_app_py39/models.py delete mode 100644 docs_src/sql_databases/sql_app_py39/schemas.py delete mode 100644 docs_src/sql_databases/sql_app_py39/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py create mode 100644 docs_src/sql_databases/tutorial001.py create mode 100644 docs_src/sql_databases/tutorial001_an.py create mode 100644 docs_src/sql_databases/tutorial001_an_py310.py create mode 100644 docs_src/sql_databases/tutorial001_an_py39.py create mode 100644 docs_src/sql_databases/tutorial001_py310.py create mode 100644 docs_src/sql_databases/tutorial001_py39.py create mode 100644 docs_src/sql_databases/tutorial002.py create mode 100644 docs_src/sql_databases/tutorial002_an.py create mode 100644 docs_src/sql_databases/tutorial002_an_py310.py create mode 100644 docs_src/sql_databases/tutorial002_an_py39.py create mode 100644 docs_src/sql_databases/tutorial002_py310.py create mode 100644 docs_src/sql_databases/tutorial002_py39.py create mode 100644 scripts/playwright/sql_databases/image01.py create mode 100644 scripts/playwright/sql_databases/image02.py delete mode 100644 tests/test_tutorial/test_async_sql_databases/__init__.py delete mode 100644 tests/test_tutorial/test_async_sql_databases/test_tutorial001.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py create mode 100644 tests/test_tutorial/test_sql_databases/test_tutorial001.py create mode 100644 tests/test_tutorial/test_sql_databases/test_tutorial002.py diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md deleted file mode 100644 index 71b29f9b7..000000000 --- a/docs/em/docs/advanced/testing-database.md +++ /dev/null @@ -1,101 +0,0 @@ -# 🔬 💽 - -👆 💪 ⚙️ 🎏 🔗 🔐 ⚪️➡️ [🔬 🔗 ⏮️ 🔐](testing-dependencies.md){.internal-link target=_blank} 📉 💽 🔬. - -👆 💪 💚 ⚒ 🆙 🎏 💽 🔬, 💾 💽 ⏮️ 💯, 🏤-🥧 ⚫️ ⏮️ 🔬 💽, ♒️. - -👑 💭 ⚫️❔ 🎏 👆 👀 👈 ⏮️ 📃. - -## 🚮 💯 🗄 📱 - -➡️ ℹ 🖼 ⚪️➡️ [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} ⚙️ 🔬 💽. - -🌐 📱 📟 🎏, 👆 💪 🚶 🔙 👈 📃 ✅ ❔ ⚫️. - -🕴 🔀 📥 🆕 🔬 📁. - -👆 😐 🔗 `get_db()` 🔜 📨 💽 🎉. - -💯, 👆 💪 ⚙️ 🔗 🔐 📨 👆 *🛃* 💽 🎉 ↩️ 1️⃣ 👈 🔜 ⚙️ 🛎. - -👉 🖼 👥 🔜 ✍ 🍕 💽 🕴 💯. - -## 📁 📊 - -👥 ✍ 🆕 📁 `sql_app/tests/test_sql_app.py`. - -🆕 📁 📊 👀 💖: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## ✍ 🆕 💽 🎉 - -🥇, 👥 ✍ 🆕 💽 🎉 ⏮️ 🆕 💽. - -💯 👥 🔜 ⚙️ 📁 `test.db` ↩️ `sql_app.db`. - -✋️ 🎂 🎉 📟 🌅 ⚖️ 🌘 🎏, 👥 📁 ⚫️. - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯‍♂️ `database.py` & `tests/test_sql_app.py`. - -🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. - -/// - -## ✍ 💽 - -↩️ 🔜 👥 🔜 ⚙️ 🆕 💽 🆕 📁, 👥 💪 ⚒ 💭 👥 ✍ 💽 ⏮️: - -```Python -Base.metadata.create_all(bind=engine) -``` - -👈 🛎 🤙 `main.py`, ✋️ ⏸ `main.py` ⚙️ 💽 📁 `sql_app.db`, & 👥 💪 ⚒ 💭 👥 ✍ `test.db` 💯. - -👥 🚮 👈 ⏸ 📥, ⏮️ 🆕 📁. - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 🔗 🔐 - -🔜 👥 ✍ 🔗 🔐 & 🚮 ⚫️ 🔐 👆 📱. - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. - -/// - -## 💯 📱 - -⤴️ 👥 💪 💯 📱 🛎. - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -& 🌐 🛠️ 👥 ⚒ 💽 ⏮️ 💯 🔜 `test.db` 💽 ↩️ 👑 `sql_app.db`. diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index d25b77894..000000000 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,576 +0,0 @@ -# 🗄 (🔗) 💽 ⏮️ 🏒 - -/// warning - -🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. - -💭 🆓 🚶 👉. - -/// - -🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜. - -🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ 🏒 🐜, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**. - -/// warning | "🐍 3️⃣.7️⃣ ➕ ✔" - -👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. - -/// - -## 🏒 🔁 - -🏒 🚫 🔧 🔁 🛠️, ⚖️ ⏮️ 👫 🤯. - -🏒 ✔️ 🏋️ 🔑 🔃 🚮 🔢 & 🔃 ❔ ⚫️ 🔜 ⚙️. - -🚥 👆 🛠️ 🈸 ⏮️ 🗝 🚫-🔁 🛠️, & 💪 👷 ⏮️ 🌐 🚮 🔢, **⚫️ 💪 👑 🧰**. - -✋️ 🚥 👆 💪 🔀 🔢, 🐕‍🦺 🌖 🌘 1️⃣ 🔁 💽, 👷 ⏮️ 🔁 🛠️ (💖 FastAPI), ♒️, 👆 🔜 💪 🚮 🏗 ➕ 📟 🔐 👈 🔢. - -👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI. - -/// note | "📡 ℹ" - -👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, , 🇵🇷. - -/// - -## 🎏 📱 - -👥 🔜 ✍ 🎏 🈸 🇸🇲 🔰 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}). - -🌅 📟 🤙 🎏. - -, 👥 🔜 🎯 🕴 🔛 🔺. - -## 📁 📊 - -➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -👉 🌖 🎏 📊 👥 ✔️ 🇸🇲 🔰. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ✍ 🏒 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🐩 🏒 📟 - -➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽: - -```Python hl_lines="3 5 22" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. - -/// - -#### 🗒 - -❌: - -```Python -check_same_thread=False -``` - -🌓 1️⃣ 🇸🇲 🔰: - -```Python -connect_args={"check_same_thread": False} -``` - -...⚫️ 💪 🕴 `SQLite`. - -/// info | "📡 ℹ" - -⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. - -/// - -### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` - -👑 ❔ ⏮️ 🏒 & FastAPI 👈 🏒 ⚓️ 🙇 🔛 🐍 `threading.local`, & ⚫️ 🚫 ✔️ 🎯 🌌 🔐 ⚫️ ⚖️ ➡️ 👆 🍵 🔗/🎉 🔗 (🔨 🇸🇲 🔰). - -& `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍. - -/// note | "📡 ℹ" - -`threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. - -👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅‍♂ 🌖, 🙅‍♂ 🌘. - -⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. - -✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. - -/// - -✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒. - -👥 🔜 ⚙️ 👈. ⚫️ 🤙 `contextvars`. - -👥 🔜 🔐 🔗 🍕 🏒 👈 ⚙️ `threading.local` & ❎ 👫 ⏮️ `contextvars`, ⏮️ 🔗 ℹ. - -👉 5️⃣📆 😑 🍖 🏗 (& ⚫️ 🤙), 👆 🚫 🤙 💪 🍕 🤔 ❔ ⚫️ 👷 ⚙️ ⚫️. - -👥 🔜 ✍ `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒. - -⚫️ ✔️ 🌐 ⚛ ⚒ 🏒 ⚙️ `contextvars` ↩️ `threading.local`. - -`contextvars` 👷 🍖 🎏 🌘 `threading.local`. ✋️ 🎂 🏒 🔗 📟 🤔 👈 👉 🎓 👷 ⏮️ `threading.local`. - -, 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI. - -/// tip - -👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. - -✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. - -/// - -### ⚙️ 🛃 `PeeweeConnectionState` 🎓 - -🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. - -/// - -/// tip - -👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. - -/// - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🏒 🏷 👆 💽 - -🔜 ✍ 🏒 🏷 (🎓) `User` & `Item`. - -👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰. - -/// tip - -🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - -✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -/// - -🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. - -```Python hl_lines="3 6-12 15-21" -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -/// tip - -🏒 ✍ 📚 🎱 🔢. - -⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. - -⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. - - `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. - -/// - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -/// tip - -❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - -👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - -👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -/// - -### ✍ Pydantic *🏷* / 🔗 - -✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -/// tip - -📥 👥 🏗 🏷 ⏮️ `id`. - -👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. - -👥 ❎ 🎱 `owner_id` 🔢 `Item`. - -/// - -### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗 - -🕐❔ 👆 🔐 💛 🏒 🎚, 💖 `some_user.items`, 🏒 🚫 🚚 `list` `Item`. - -⚫️ 🚚 🎁 🛃 🎚 🎓 `ModelSelect`. - -⚫️ 💪 ✍ `list` 🚮 🏬 ⏮️ `list(some_user.items)`. - -✋️ 🎚 ⚫️ 🚫 `list`. & ⚫️ 🚫 ☑ 🐍 🚂. ↩️ 👉, Pydantic 🚫 💭 🔢 ❔ 🗜 ⚫️ `list` Pydantic *🏷* / 🔗. - -✋️ ⏮️ ⏬ Pydantic ✔ 🚚 🛃 🎓 👈 😖 ⚪️➡️ `pydantic.utils.GetterDict`, 🚚 🛠️ ⚙️ 🕐❔ ⚙️ `orm_mode = True` 🗃 💲 🐜 🏷 🔢. - -👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`. - -& 🚥 👈 💼, 📨 `list` ⏮️ ⚫️. - -& ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`. - -/// tip - -👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. - -/// - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -### ✍ 🌐 💩 🇨🇻 - -✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -📤 🔺 ⏮️ 📟 🇸🇲 🔰. - -👥 🚫 🚶‍♀️ `db` 🔢 🤭. ↩️ 👥 ⚙️ 🏷 🔗. 👉 ↩️ `db` 🎚 🌐 🎚, 👈 🔌 🌐 🔗 ⚛. 👈 ⚫️❔ 👥 ✔️ 🌐 `contextvars` ℹ 🔛. - -🆖, 🕐❔ 🛬 📚 🎚, 💖 `get_users`, 👥 🔗 🤙 `list`, 💖: - -```Python -list(models.User.select()) -``` - -👉 🎏 🤔 👈 👥 ✔️ ✍ 🛃 `PeeweeGetterDict`. ✋️ 🛬 🕳 👈 ⏪ `list` ↩️ `peewee.ModelSelect` `response_model` *➡ 🛠️* ⏮️ `List[models.User]` (👈 👥 🔜 👀 ⏪) 🔜 👷 ☑. - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -```Python hl_lines="9-11" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### ✍ 🔗 - -✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚: - -```Python hl_lines="23-29" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗. - -⚫️ 🔗 💽 & ♻ 🔗 💽 🔗 🔢 👈 🔬 🔠 📨 (⚙️ `contextvars` 🎱 ⚪️➡️ 🔛). - -↩️ 💽 🔗 ⚠ 👤/🅾 🚧, 👉 🔗 ✍ ⏮️ 😐 `def` 🔢. - -& ⤴️, 🔠 *➡ 🛠️ 🔢* 👈 💪 🔐 💽 👥 🚮 ⚫️ 🔗. - -✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨‍🎨* `dependencies` 🔢: - -```Python hl_lines="32 40 47 59 65 72" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔑 🔢 🎧-🔗 - -🌐 `contextvars` 🍕 👷, 👥 💪 ⚒ 💭 👥 ✔️ 🔬 💲 `ContextVar` 🔠 📨 👈 ⚙️ 💽, & 👈 💲 🔜 ⚙️ 💽 🇵🇸 (🔗, 💵, ♒️) 🎂 📨. - -👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️). - -```Python hl_lines="18-20" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -**⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). - -/// tip - -FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. - -✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. - - & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. - -/// - -#### 🏒 🗳 - -🚥 👆 ⚙️ 🏒 🗳, ☑ 💽 `db.obj`. - -, 👆 🔜 ⏲ ⚫️ ⏮️: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔃 `def` 🆚 `async def` - -🎏 ⏮️ 🇸🇲, 👥 🚫 🔨 🕳 💖: - -```Python -user = await models.User.select().first() -``` - -...✋️ ↩️ 👥 ⚙️: - -```Python -user = models.User.select().first() -``` - -, 🔄, 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## 🔬 🏒 ⏮️ 🔁 - -👉 🖼 🔌 ➕ *➡ 🛠️* 👈 🔬 📏 🏭 📨 ⏮️ `time.sleep(sleep_time)`. - -⚫️ 🔜 ✔️ 💽 🔗 📂 ▶️ & 🔜 ⌛ 🥈 ⏭ 🙇 🔙. & 🔠 🆕 📨 🔜 ⌛ 🕐 🥈 🌘. - -👉 🔜 💪 ➡️ 👆 💯 👈 👆 📱 ⏮️ 🏒 & FastAPI 🎭 ☑ ⏮️ 🌐 💩 🔃 🧵. - -🚥 👆 💚 ✅ ❔ 🏒 🔜 💔 👆 📱 🚥 ⚙️ 🍵 🛠️, 🚶 `sql_app/database.py` 📁 & 🏤 ⏸: - -```Python -# db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, 🏤 💪 `async` 🔗 `reset_db_state()` & ❎ ⚫️ ⏮️ `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -⤴️ 🏃 👆 📱 ⏮️ Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -📂 👆 🖥 http://127.0.0.1:8000/docs & ✍ 👩‍❤‍👨 👩‍💻. - -⤴️ 📂 1️⃣0️⃣ 📑 http://127.0.0.1:8000/docs#/default/read_🐌_👩‍💻_slowusers_ = 🎏 🕰. - -🚶 *➡ 🛠️* "🤚 `/slowusers/`" 🌐 📑. ⚙️ "🔄 ⚫️ 👅" 🔼 & 🛠️ 📨 🔠 📑, 1️⃣ ▶️️ ⏮️ 🎏. - -📑 🔜 ⌛ 🍖 & ⤴️ 👫 🔜 🎦 `Internal Server Error`. - -### ⚫️❔ 🔨 - -🥇 📑 🔜 ⚒ 👆 📱 ✍ 🔗 💽 & ⌛ 🥈 ⏭ 🙇 🔙 & 📪 💽 🔗. - -⤴️, 📨 ⏭ 📑, 👆 📱 🔜 ⌛ 🕐 🥈 🌘, & 🔛. - -👉 ⛓ 👈 ⚫️ 🔜 🔚 🆙 🏁 🏁 📑' 📨 ⏪ 🌘 ⏮️ 🕐. - -⤴️ 1️⃣ 🏁 📨 👈 ⌛ 🌘 🥈 🔜 🔄 📂 💽 🔗, ✋️ 1️⃣ 📚 ⏮️ 📨 🎏 📑 🔜 🎲 🍵 🎏 🧵 🥇 🕐, ⚫️ 🔜 ✔️ 🎏 💽 🔗 👈 ⏪ 📂, & 🏒 🔜 🚮 ❌ & 👆 🔜 👀 ⚫️ 📶, & 📨 🔜 ✔️ `Internal Server Error`. - -👉 🔜 🎲 🔨 🌅 🌘 1️⃣ 📚 📑. - -🚥 👆 ✔️ 💗 👩‍💻 💬 👆 📱 ⚫️❔ 🎏 🕰, 👉 ⚫️❔ 💪 🔨. - -& 👆 📱 ▶️ 🍵 🌅 & 🌖 👩‍💻 🎏 🕰, ⌛ 🕰 👁 📨 💪 📏 & 📏 ⏲ ❌. - -### 🔧 🏒 ⏮️ FastAPI - -🔜 🚶 🔙 📁 `sql_app/database.py`, & ✍ ⏸: - -```Python -db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, ✍ 💪 `async` 🔗 `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -❎ 👆 🏃‍♂ 📱 & ▶️ ⚫️ 🔄. - -🔁 🎏 🛠️ ⏮️ 1️⃣0️⃣ 📑. 👉 🕰 🌐 👫 🔜 ⌛ & 👆 🔜 🤚 🌐 🏁 🍵 ❌. - -...👆 🔧 ⚫️ ❗ - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` (⚖️ 👐 👆 💚) 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## 📡 ℹ - -/// warning - -👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. - -/// - -### ⚠ - -🏒 ⚙️ `threading.local` 🔢 🏪 ⚫️ 💽 "🇵🇸" 💽 (🔗, 💵, ♒️). - -`threading.local` ✍ 💲 🌟 ⏮️ 🧵, ✋️ 🔁 🛠️ 🔜 🏃 🌐 📟 (✅ 🔠 📨) 🎏 🧵, & 🎲 🚫 ✔. - -🔛 🔝 👈, 🔁 🛠️ 💪 🏃 🔁 📟 🧵 (⚙️ `asyncio.run_in_executor`), ✋️ 🔗 🎏 📨. - -👉 ⛓ 👈, ⏮️ 🏒 ⏮️ 🛠️, 💗 📋 💪 ⚙️ 🎏 `threading.local` 🔢 & 🔚 🆙 🤝 🎏 🔗 & 💽 (👈 👫 🚫🔜 🚫), & 🎏 🕰, 🚥 👫 🛠️ 🔁 👤/🅾-🚧 📟 🧵 (⏮️ 😐 `def` 🔢 FastAPI, *➡ 🛠️* & 🔗), 👈 📟 🏆 🚫 ✔️ 🔐 💽 🇵🇸 🔢, ⏪ ⚫️ 🍕 🎏 📨 & ⚫️ 🔜 💪 🤚 🔐 🎏 💽 🇵🇸. - -### 🔑 🔢 - -🐍 3️⃣.7️⃣ ✔️ `contextvars` 👈 💪 ✍ 🇧🇿 🔢 📶 🎏 `threading.local`, ✋️ 🔗 👫 🔁 ⚒. - -📤 📚 👜 ✔️ 🤯. - -`ContextVar` ✔️ ✍ 🔝 🕹, 💖: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -⚒ 💲 ⚙️ ⏮️ "🔑" (✅ ⏮️ 📨) ⚙️: - -```Python -some_var.set("new value") -``` - -🤚 💲 🙆 🔘 🔑 (✅ 🙆 🍕 🚚 ⏮️ 📨) ⚙️: - -```Python -some_var.get() -``` - -### ⚒ 🔑 🔢 `async` 🔗 `reset_db_state()` - -🚥 🍕 🔁 📟 ⚒ 💲 ⏮️ `some_var.set("updated in function")` (✅ 💖 `async` 🔗), 🎂 📟 ⚫️ & 📟 👈 🚶 ⏮️ (✅ 📟 🔘 `async` 🔢 🤙 ⏮️ `await`) 🔜 👀 👈 🆕 💲. - -, 👆 💼, 🚥 👥 ⚒ 🏒 🇵🇸 🔢 (⏮️ 🔢 `dict`) `async` 🔗, 🌐 🎂 🔗 📟 👆 📱 🔜 👀 👉 💲 & 🔜 💪 ♻ ⚫️ 🎂 📨. - -& 🔑 🔢 🔜 ⚒ 🔄 ⏭ 📨, 🚥 👫 🛠️. - -### ⚒ 💽 🇵🇸 🔗 `get_db()` - -`get_db()` 😐 `def` 🔢, **FastAPI** 🔜 ⚒ ⚫️ 🏃 🧵, ⏮️ *📁* "🔑", 🧑‍🤝‍🧑 🎏 💲 🔑 🔢 ( `dict` ⏮️ ⏲ 💽 🇵🇸). ⤴️ ⚫️ 💪 🚮 💽 🇵🇸 👈 `dict`, 💖 🔗, ♒️. - -✋️ 🚥 💲 🔑 🔢 (🔢 `dict`) ⚒ 👈 😐 `def` 🔢, ⚫️ 🔜 ✍ 🆕 💲 👈 🔜 🚧 🕴 👈 🧵 🧵, & 🎂 📟 (💖 *➡ 🛠️ 🔢*) 🚫🔜 ✔️ 🔐 ⚫️. `get_db()` 👥 💪 🕴 ⚒ 💲 `dict`, ✋️ 🚫 🎂 `dict` ⚫️. - -, 👥 💪 ✔️ `async` 🔗 `reset_db_state()` ⚒ `dict` 🔑 🔢. 👈 🌌, 🌐 📟 ✔️ 🔐 🎏 `dict` 💽 🇵🇸 👁 📨. - -### 🔗 & 🔌 🔗 `get_db()` - -⤴️ ⏭ ❔ 🔜, ⚫️❔ 🚫 🔗 & 🔌 💽 `async` 🔗 ⚫️, ↩️ `get_db()`❓ - -`async` 🔗 ✔️ `async` 🔑 🔢 🛡 🎂 📨, ✋️ 🏗 & 📪 💽 🔗 ⚠ 🚧, ⚫️ 💪 📉 🎭 🚥 ⚫️ 📤. - -👥 💪 😐 `def` 🔗 `get_db()`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md deleted file mode 100644 index 2b704f229..000000000 --- a/docs/en/docs/advanced/testing-database.md +++ /dev/null @@ -1,111 +0,0 @@ -# Testing a Database - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. - -The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -/// - -You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. - -You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. - -The main idea is exactly the same you saw in that previous chapter. - -## Add tests for the SQL app - -Let's update the example from [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} to use a testing database. - -All the app code is the same, you can go back to that chapter check how it was. - -The only changes here are in the new testing file. - -Your normal dependency `get_db()` would return a database session. - -In the test, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. - -In this example we'll create a temporary database only for the tests. - -## File structure - -We create a new file at `sql_app/tests/test_sql_app.py`. - -So the new file structure looks like: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## Create the new database session - -First, we create a new database session with the new database. - -We'll use an in-memory database that persists during the tests instead of the local file `sql_app.db`. - -But the rest of the session code is more or less the same, we just copy it. - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - -For simplicity and to focus on the specific testing code, we are just copying it. - -/// - -## Create the database - -Because now we are going to use a new database in a new file, we need to make sure we create the database with: - -```Python -Base.metadata.create_all(bind=engine) -``` - -That is normally called in `main.py`, but the line in `main.py` uses the database file `sql_app.db`, and we need to make sure we create `test.db` for the tests. - -So we add that line here, with the new file. - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## Dependency override - -Now we create the dependency override and add it to the overrides for our app. - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. - -/// - -## Test the app - -Then we can just test the app as normally. - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md deleted file mode 100644 index a72316c4d..000000000 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ /dev/null @@ -1,201 +0,0 @@ -# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1. - -The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. - -/// - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. - -It is compatible with: - -* PostgreSQL -* MySQL -* SQLite - -In this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is. - -Later, for your production application, you might want to use a database server like **PostgreSQL**. - -/// tip - -You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. - -This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. - -/// - -## Import and set up `SQLAlchemy` - -* Import `SQLAlchemy`. -* Create a `metadata` object. -* Create a table `notes` using the `metadata` object. - -```Python hl_lines="4 14 16-22" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// tip - -Notice that all this code is pure SQLAlchemy Core. - -`databases` is not doing anything here yet. - -/// - -## Import and set up `databases` - -* Import `databases`. -* Create a `DATABASE_URL`. -* Create a `database` object. - -```Python hl_lines="3 9 12" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// tip - -If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. - -/// - -## Create the tables - -In this case, we are creating the tables in the same Python file, but in production, you would probably want to create them with Alembic, integrated with migrations, etc. - -Here, this section would run directly, right before starting your **FastAPI** application. - -* Create an `engine`. -* Create all the tables from the `metadata` object. - -```Python hl_lines="25-28" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Create models - -Create Pydantic models for: - -* Notes to be created (`NoteIn`). -* Notes to be returned (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). - -So, you will be able to see it all in the interactive API docs. - -## Connect and disconnect - -* Create your `FastAPI` application. -* Create event handlers to connect and disconnect from the database. - -```Python hl_lines="42 45-47 50-52" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Read notes - -Create the *path operation function* to read notes: - -```Python hl_lines="55-58" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// note - -Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -/// - -### Notice the `response_model=List[Note]` - -It uses `typing.List`. - -That documents (and validates, serializes, filters) the output data, as a `list` of `Note`s. - -## Create notes - -Create the *path operation function* to create notes: - -```Python hl_lines="61-65" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// info - -In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - -The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - -/// - -/// note - -Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -/// - -### About `{**note.dict(), "id": last_record_id}` - -`note` is a Pydantic `Note` object. - -`note.dict()` returns a `dict` with its data, something like: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -but it doesn't have the `id` field. - -So we create a new `dict`, that contains the key-value pairs from `note.dict()` with: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -And then, we extend that copy `dict`, adding another key-value pair: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -So, the final result returned would be something like: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## Check it - -You can copy this code as is, and see the docs at http://127.0.0.1:8000/docs. - -There you can see all your API documented and interact with it: - - - -## More info - -You can read more about `encode/databases` at its GitHub page. diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md deleted file mode 100644 index feb4025dd..000000000 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ /dev/null @@ -1,178 +0,0 @@ -# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1. - -The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. - -/// - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -**FastAPI** can also be integrated with any NoSQL. - -Here we'll see an example using **Couchbase**, a document based NoSQL database. - -You can adapt it to any other NoSQL database like: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch**, etc. - -/// tip - -There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase - -/// - -## Import Couchbase components - -For now, don't pay attention to the rest, only the imports: - -```Python hl_lines="3-5" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Define a constant to use as a "document type" - -We will use it later as a fixed field `type` in our documents. - -This is not required by Couchbase, but is a good practice that will help you afterwards. - -```Python hl_lines="9" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Add a function to get a `Bucket` - -In **Couchbase**, a bucket is a set of documents, that can be of different types. - -They are generally all related to the same application. - -The analogy in the relational database world would be a "database" (a specific database, not the database server). - -The analogy in **MongoDB** would be a "collection". - -In the code, a `Bucket` represents the main entrypoint of communication with the database. - -This utility function will: - -* Connect to a **Couchbase** cluster (that might be a single machine). - * Set defaults for timeouts. -* Authenticate in the cluster. -* Get a `Bucket` instance. - * Set defaults for timeouts. -* Return it. - -```Python hl_lines="12-21" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Create Pydantic models - -As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic. - -### `User` model - -First, let's create a `User` model: - -```Python hl_lines="24-28" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. - -### `UserInDB` model - -Now, let's create a `UserInDB` model. - -This will have the data that is actually stored in the database. - -We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: - -```Python hl_lines="31-33" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -/// note - -Notice that we have a `hashed_password` and a `type` field that will be stored in the database. - -But it is not part of the general `User` model (the one we will return in the *path operation*). - -/// - -## Get the user - -Now create a function that will: - -* Take a username. -* Generate a document ID from it. -* Get the document with that ID. -* Put the contents of the document in a `UserInDB` model. - -By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add unit tests for it: - -```Python hl_lines="36-42" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string". - -Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string. - -### `dict` unpacking - -If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking". - -It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments. - -So, if the `dict` contains: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -It will be passed to `UserInDB` as: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## Create your **FastAPI** code - -### Create the `FastAPI` app - -```Python hl_lines="46" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Create the *path operation function* - -As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`. - -Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions: - -```Python hl_lines="49-53" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Recap - -You can integrate any third party NoSQL database, just using their standard packages. - -The same applies to any other external tool, system or API. diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index e73ca369b..000000000 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,594 +0,0 @@ -# ~~SQL (Relational) Databases with Peewee~~ (deprecated) - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -/// warning - -If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - -Feel free to skip this. - -Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. - -/// - -/// info - -These docs assume Pydantic v1. - -Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. - -The examples here are no longer tested in CI (as they were before). - -/// - -If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. - -If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. - -/// warning | "Python 3.7+ required" - -You will need Python 3.7 or above to safely use Peewee with FastAPI. - -/// - -## Peewee for async - -Peewee was not designed for async frameworks, or with them in mind. - -Peewee has some heavy assumptions about its defaults and about how it should be used. - -If you are developing an application with an older non-async framework, and can work with all its defaults, **it can be a great tool**. - -But if you need to change some of the defaults, support more than one predefined database, work with an async framework (like FastAPI), etc, you will need to add quite some complex extra code to override those defaults. - -Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. - -/// note | "Technical Details" - -You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. - -/// - -## The same app - -We are going to create the same application as in the SQLAlchemy tutorial ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}). - -Most of the code is actually the same. - -So, we are going to focus only on the differences. - -## File structure - -Let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -This is almost the same structure as we had for the SQLAlchemy tutorial. - -Now let's see what each file/module does. - -## Create the Peewee parts - -Let's refer to the file `sql_app/database.py`. - -### The standard Peewee code - -Let's first check all the normal Peewee code, create a Peewee database: - -```Python hl_lines="3 5 22" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. - -/// - -#### Note - -The argument: - -```Python -check_same_thread=False -``` - -is equivalent to the one in the SQLAlchemy tutorial: - -```Python -connect_args={"check_same_thread": False} -``` - -...it is needed only for `SQLite`. - -/// info | "Technical Details" - -Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. - -/// - -### Make Peewee async-compatible `PeeweeConnectionState` - -The main issue with Peewee and FastAPI is that Peewee relies heavily on Python's `threading.local`, and it doesn't have a direct way to override it or let you handle connections/sessions directly (as is done in the SQLAlchemy tutorial). - -And `threading.local` is not compatible with the new async features of modern Python. - -/// note | "Technical Details" - -`threading.local` is used to have a "magic" variable that has a different value for each thread. - -This was useful in older frameworks designed to have one single thread per request, no more, no less. - -Using this, each request would have its own database connection/session, which is the actual final goal. - -But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. - -/// - -But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features. - -We are going to use that. It's called `contextvars`. - -We are going to override the internal parts of Peewee that use `threading.local` and replace them with `contextvars`, with the corresponding updates. - -This might seem a bit complex (and it actually is), you don't really need to completely understand how it works to use it. - -We will create a `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -This class inherits from a special internal class used by Peewee. - -It has all the logic to make Peewee use `contextvars` instead of `threading.local`. - -`contextvars` works a bit differently than `threading.local`. But the rest of Peewee's internal code assumes that this class works with `threading.local`. - -So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI. - -/// tip - -This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. - -But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. - -/// - -### Use the custom `PeeweeConnectionState` class - -Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -Make sure you overwrite `db._state` *after* creating `db`. - -/// - -/// tip - -You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. - -/// - -## Create the database models - -Let's now see the file `sql_app/models.py`. - -### Create Peewee models for our data - -Now create the Peewee models (classes) for `User` and `Item`. - -This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial. - -/// tip - -Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. - -But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. - -/// - -Import `db` from `database` (the file `database.py` from above) and use it here. - -```Python hl_lines="3 6-12 15-21" -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -/// tip - -Peewee creates several magic attributes. - -It will automatically add an `id` attribute as an integer to be the primary key. - -It will chose the name of the tables based on the class names. - -For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. - -/// - -## Create the Pydantic models - -Now let's check the file `sql_app/schemas.py`. - -/// tip - -To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. - -These Pydantic models define more or less a "schema" (a valid data shape). - -So this will help us avoiding confusion while using both. - -/// - -### Create the Pydantic *models* / schemas - -Create all the same Pydantic models as in the SQLAlchemy tutorial: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -/// tip - -Here we are creating the models with an `id`. - -We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. - -We are also adding the magic `owner_id` attribute to `Item`. - -/// - -### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas - -When you access a relationship in a Peewee object, like in `some_user.items`, Peewee doesn't provide a `list` of `Item`. - -It provides a special custom object of class `ModelSelect`. - -It's possible to create a `list` of its items with `list(some_user.items)`. - -But the object itself is not a `list`. And it's also not an actual Python generator. Because of this, Pydantic doesn't know by default how to convert it to a `list` of Pydantic *models* / schemas. - -But recent versions of Pydantic allow providing a custom class that inherits from `pydantic.utils.GetterDict`, to provide the functionality used when using the `orm_mode = True` to retrieve the values for ORM model attributes. - -We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. - -And if that's the case, just return a `list` with it. - -And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`. - -/// tip - -We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. - -/// - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -### Create all the CRUD utils - -Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -There are some differences with the code for the SQLAlchemy tutorial. - -We don't pass a `db` attribute around. Instead we use the models directly. This is because the `db` object is a global object, that includes all the connection logic. That's why we had to do all the `contextvars` updates above. - -Aso, when returning several objects, like in `get_users`, we directly call `list`, like in: - -```Python -list(models.User.select()) -``` - -This is for the same reason that we had to create a custom `PeeweeGetterDict`. But by returning something that is already a `list` instead of the `peewee.ModelSelect` the `response_model` in the *path operation* with `List[models.User]` (that we'll see later) will work correctly. - -## Main **FastAPI** app - -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. - -### Create the database tables - -In a very simplistic way create the database tables: - -```Python hl_lines="9-11" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Create a dependency - -Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: - -```Python hl_lines="23-29" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -Here we have an empty `yield` because we are actually not using the database object directly. - -It is connecting to the database and storing the connection data in an internal variable that is independent for each request (using the `contextvars` tricks from above). - -Because the database connection is potentially I/O blocking, this dependency is created with a normal `def` function. - -And then, in each *path operation function* that needs to access the database we add it as a dependency. - -But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: - -```Python hl_lines="32 40 47 59 65 72" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Context variable sub-dependency - -For all the `contextvars` parts to work, we need to make sure we have an independent value in the `ContextVar` for each request that uses the database, and that value will be used as the database state (connection, transactions, etc) for the whole request. - -For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). - -```Python hl_lines="18-20" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). - -/// tip - -As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. - -But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. - -And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. - -/// - -#### Peewee Proxy - -If you are using a Peewee Proxy, the actual database is at `db.obj`. - -So, you would reset it with: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### About `def` vs `async def` - -The same as with SQLAlchemy, we are not doing something like: - -```Python -user = await models.User.select().first() -``` - -...but instead we are using: - -```Python -user = models.User.select().first() -``` - -So, again, we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## Testing Peewee with async - -This example includes an extra *path operation* that simulates a long processing request with `time.sleep(sleep_time)`. - -It will have the database connection open at the beginning and will just wait some seconds before replying back. And each new request will wait one second less. - -This will easily let you test that your app with Peewee and FastAPI is behaving correctly with all the stuff about threads. - -If you want to check how Peewee would break your app if used without modification, go the `sql_app/database.py` file and comment the line: - -```Python -# db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, comment the body of the `async` dependency `reset_db_state()` and replace it with a `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -Then run your app with Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Open your browser at http://127.0.0.1:8000/docs and create a couple of users. - -Then open 10 tabs at http://127.0.0.1:8000/docs#/default/read_slow_users_slowusers__get at the same time. - -Go to the *path operation* "Get `/slowusers/`" in all of the tabs. Use the "Try it out" button and execute the request in each tab, one right after the other. - -The tabs will wait for a bit and then some of them will show `Internal Server Error`. - -### What happens - -The first tab will make your app create a connection to the database and wait for some seconds before replying back and closing the database connection. - -Then, for the request in the next tab, your app will wait for one second less, and so on. - -This means that it will end up finishing some of the last tabs' requests earlier than some of the previous ones. - -Then one the last requests that wait less seconds will try to open a database connection, but as one of those previous requests for the other tabs will probably be handled in the same thread as the first one, it will have the same database connection that is already open, and Peewee will throw an error and you will see it in the terminal, and the response will have an `Internal Server Error`. - -This will probably happen for more than one of those tabs. - -If you had multiple clients talking to your app exactly at the same time, this is what could happen. - -And as your app starts to handle more and more clients at the same time, the waiting time in a single request needs to be shorter and shorter to trigger the error. - -### Fix Peewee with FastAPI - -Now go back to the file `sql_app/database.py`, and uncomment the line: - -```Python -db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, uncomment the body of the `async` dependency `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -Terminate your running app and start it again. - -Repeat the same process with the 10 tabs. This time all of them will wait and you will get all the results without errors. - -...You fixed it! - -## Review all the files - - Remember you should have a directory named `my_super_project` (or however you want) that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## Technical Details - -/// warning - -These are very technical details that you probably don't need. - -/// - -### The problem - -Peewee uses `threading.local` by default to store it's database "state" data (connection, transactions, etc). - -`threading.local` creates a value exclusive to the current thread, but an async framework would run all the code (e.g. for each request) in the same thread, and possibly not in order. - -On top of that, an async framework could run some sync code in a threadpool (using `asyncio.run_in_executor`), but belonging to the same request. - -This means that, with Peewee's current implementation, multiple tasks could be using the same `threading.local` variable and end up sharing the same connection and data (that they shouldn't), and at the same time, if they execute sync I/O-blocking code in a threadpool (as with normal `def` functions in FastAPI, in *path operations* and dependencies), that code won't have access to the database state variables, even while it's part of the same request and it should be able to get access to the same database state. - -### Context variables - -Python 3.7 has `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. - -There are several things to keep in mind. - -The `ContextVar` has to be created at the top of the module, like: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -To set a value used in the current "context" (e.g. for the current request) use: - -```Python -some_var.set("new value") -``` - -To get a value anywhere inside of the context (e.g. in any part handling the current request) use: - -```Python -some_var.get() -``` - -### Set context variables in the `async` dependency `reset_db_state()` - -If some part of the async code sets the value with `some_var.set("updated in function")` (e.g. like the `async` dependency), the rest of the code in it and the code that goes after (including code inside of `async` functions called with `await`) will see that new value. - -So, in our case, if we set the Peewee state variable (with a default `dict`) in the `async` dependency, all the rest of the internal code in our app will see this value and will be able to reuse it for the whole request. - -And the context variable would be set again for the next request, even if they are concurrent. - -### Set database state in the dependency `get_db()` - -As `get_db()` is a normal `def` function, **FastAPI** will make it run in a threadpool, with a *copy* of the "context", holding the same value for the context variable (the `dict` with the reset database state). Then it can add database state to that `dict`, like the connection, etc. - -But if the value of the context variable (the default `dict`) was set in that normal `def` function, it would create a new value that would stay only in that thread of the threadpool, and the rest of the code (like the *path operation functions*) wouldn't have access to it. In `get_db()` we can only set values in the `dict`, but not the entire `dict` itself. - -So, we need to have the `async` dependency `reset_db_state()` to set the `dict` in the context variable. That way, all the code has access to the same `dict` for the database state for a single request. - -### Connect and disconnect in the dependency `get_db()` - -Then the next question would be, why not just connect and disconnect the database in the `async` dependency itself, instead of in `get_db()`? - -The `async` dependency has to be `async` for the context variable to be preserved for the rest of the request, but creating and closing the database connection is potentially blocking, so it could degrade performance if it was there. - -So we also need the normal `def` dependency `get_db()`. diff --git a/docs/en/docs/how-to/testing-database.md b/docs/en/docs/how-to/testing-database.md new file mode 100644 index 000000000..d0ed15bca --- /dev/null +++ b/docs/en/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testing a Database + +You can study about databases, SQL, and SQLModel in the SQLModel docs. 🤓 + +There's a mini tutorial on using SQLModel with FastAPI. ✨ + +That tutorial includes a section about testing SQL databases. 😎 diff --git a/docs/en/docs/img/tutorial/sql-databases/image01.png b/docs/en/docs/img/tutorial/sql-databases/image01.png index 8e575abd65aaf37a33fed5bdae4029955dffb090..bfcdb57a0743c5fdcd453007987a19d878af1f1a 100644 GIT binary patch literal 69755 zcmd?Qbx@p5)F(pGF0pX`*X=P>QDZgV%4d(NI zzpK|T2><>-dS&)pBH+HyeDPdri1@vJF2BC`mmsr#VPRp}=bn+9yWvRU&B*gJ1kR1E zt))i$0Eo>(qawE`xd`HOt$=!5djI6$2(f@9((`{k$4RnWOgubwS7ded>Eh{s8=o|H z#J>4ER5I#Ij%PXq)c@Ko!-s!6s{A?a`j-OX4v&CfHgQovP>>bz-81RWm;b9aehB|} z6P#S?BGjT>XOnhzQRjnA@r0CjoSO4VQae_iSOBvc&JND@2a`Gc^Bp-gR|0PI(%Z*QUqja!G-tE5OpxoWi`+~a9-Ac=W@RlN2Gz<*k;o(*T>G02+k&3!; z-+z{xi6+msFLxJ>1|*;GjvZG=e?u+?8C6I14Gh1Y=g$jikNe*-y@EH_!zn?CAl;cx zXdhz-EH)E4-$jk!9gN(KvjYU_<%9`2<@3!Zo@U^bnTsNRK5~m;9+?#vI!9BBg`SES zdyh1HmJ0g{!<#C}VBb#05my{IdCS%ojOs+SF%~{Rm*C}L!*$`(^!Ez>VKIcz-e6FY4c6!g|Z;L!ag$rk$ z1F9JWX6ePK;1fa*E1!^}Rdq(+c$^ z#}_gI02jNSb`|gb>|%@g@^$@V?$R+9d{%QArf4Ip`(S2)wBain)0Kkl_6wurf?QL) zChNYnnj}sxsRHkYP4cJ&;_1TUP=F+b(*987QJc5Ks|!a~?^~W2))HTBrQxPyF~P#8 z@=xV~Po1kmN_{eNeJr(mYpcR?luxTVT9=LHTdZe`ic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T zrQ*w8W%fW_##ga-*~l*mtG9u!>tmv3Mg|Wfkv^K`MsjVxM%QsTg$%h`uC=RQDXR3U z3Gj(LJ9{DjjrbR=naTOp@+7bisR0Vv`FxEfOQ_GV?+c9}sSMq#dMEdCg1I4oUpI z>~=bTO61WWsT<3Jf;7BrPu3!_nJ>brmG8`zPiD88FX7(%JZ`nmP|q$3kz!;faxvbp zVWD2`jxuPRF(yWx*X%eKgSWS2zItX=ytRcV>R+T^HF)z&AZh{-jc%C2c22gUh2)*x zSq46-Be!cwDfU?6KipibLz{NnY&=rpiD3imQn4iCU}6(A5C{KAMZt5}+kTDwrrSV> zES|Ssv>0i;5jh}bnxFnh1sLoV^Kn}t50y?ldi3e{+v*%FRc1iSb=LR303R2qyty26 z30Dal8;5b4bxUi@r#eNkw`Kqx>$b;&XsW2&h>0e4?wo2~Rj+!88UTgVs4Xg34_mf# zR&&gMeyF>mt`K-sV(>w-64Px@Fe>W*bki|W0W~Q?2s*W8QZlzA2~fK%gx>t9TFN+f zLi=)^oUB;L6M_2XzD&rovkQ?M+OVRK^~Jr4S{&5jYwrJ&Fwdj$^k&r<2{*4{Kc_a( zmRC{9evC?8CYb;LfVC+A*Z0Qa@%vg^<0K+PfqV&5mb5k2l-)=bF>3!w8uv%2XaZ8a zEFZz_U#RfdGCy1tz=JUieQ}XRU;d$wd`=!sJ${rkpV~kO4qT_JA~@gGAIY~=s| diff --git a/docs/en/docs/img/tutorial/sql-databases/image02.png b/docs/en/docs/img/tutorial/sql-databases/image02.png index ee59fc9398a4607872d7aae1d439fdb71c0a706c..7bcad83783af805276cb25bde4d3a4b384f92600 100644 GIT binary patch literal 69197 zcmeFZRaD%;(;d)-*?WQ-M#1DhduXYcV2#0-Cf;PUDj0-^jTgK7yC6f8X6j|v=mqg4GsMd8rl=S zr;kx@q(^}~sLLYI=b|d73bmakwVhGMyc%CJ>o?!UKNv4Q zenm_e_k*TcM8in67~}D^H|XTFr}1LWVJNKsq=Daazm^=XCWFEP4b7%B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Gv~0x4)lQD z)MYb)RsPdLBXfYx-wc zB>2M6$n^!chTC_1(q5@{o^jEtwAxpV)ja#r^F^;d*bLYH7tVD1een>eA!os9y;Rc8 zJSaol?_g{0M>iGs_a=>^tctCqo3)%Pd9l@-pM!(LETu{tGI->y*JeC)`Zf41Gu`1F zV`@%ln~dbDOE*L;nDzr85%`=wf^`|Y7xq~{S5qUXmaou

```console -$ pip install sqlalchemy - +$ pip install sqlmodel ---> 100% ```
-## Create the SQLAlchemy parts - -Let's refer to the file `sql_app/database.py`. +## Create the App with a Single Model -### Import the SQLAlchemy parts +We'll create the simplest first version of the app with a single **SQLModel** model first. -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### Create a database URL for SQLAlchemy - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database). - -The file will be located at the same directory in the file `sql_app.db`. - -That's why the last part is `./sql_app.db`. - -If you were using a **PostgreSQL** database instead, you would just have to uncomment the line: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` +Later we'll improve it increasing security and versatility with **multiple models** below. 🤓 -...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other). +### Create Models -/// tip - -This is the main line that you would have to modify if you wanted to use a different database. - -/// - -### Create the SQLAlchemy `engine` +Import `SQLModel` and create a database model: -The first step is to create a SQLAlchemy "engine". +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} -We will later use this `engine` in other places. +The `Hero` class is very similar to a Pydantic model (in fact, underneath, it actually *is a Pydantic model*). -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +There are a few differences: -#### Note +* `table=True` tells SQLModel that this is a *table model*, it should represent a **table** in the SQL database, it's not just a *data model* (as would be any other regular Pydantic class). -The argument: +* `Field(primary_key=True)` tells SQLModel that the `id` is the **primary key** in the SQL database (you can learn more about SQL primary keys in the SQLModel docs). -```Python -connect_args={"check_same_thread": False} -``` + By having the type as `int | None`, SQLModel will know that this column should be an `INTEGER` in the SQL database and that it should be `NULLABLE`. -...is needed only for `SQLite`. It's not needed for other databases. +* `Field(index=True)` tells SQLModel that it should create a **SQL index** for this column, that would allow faster lookups in the database when reading data filtered by this column. -/// info | "Technical Details" + SQLModel will know that something declared as `str` will be a SQL column of type `TEXT` (or `VARCHAR`, depending on the database). -By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. +### Create an Engine -This is to prevent accidentally sharing the same connection for different things (for different requests). +A SQLModel `engine` (underneath it's actually a SQLAlchemy `engine`) is what **holds the connections** to the database. -But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. +You would have **one single `engine` object** for all your code to connect to the same database. -Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} -/// +Using `check_same_thread=False` allows FastAPI to use the same SQLite database in different threads. This is necessary as **one single request** could use **more than one thread** (for example in dependencies). -### Create a `SessionLocal` class +Don't worry, with the way the code is structured, we'll make sure we use **a single SQLModel *session* per request** later, this is actually what the `check_same_thread` is trying to achieve. -Each instance of the `SessionLocal` class will be a database session. The class itself is not a database session yet. +### Create the Tables -But once we create an instance of the `SessionLocal` class, this instance will be the actual database session. +We then add a function that uses `SQLModel.metadata.create_all(engine)` to **create the tables** for all the *table models*. -We name it `SessionLocal` to distinguish it from the `Session` we are importing from SQLAlchemy. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} -We will use `Session` (the one imported from SQLAlchemy) later. +### Create a Session Dependency -To create the `SessionLocal` class, use the function `sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +A **`Session`** is what stores the **objects in memory** and keeps track of any changes needed in the data, then it **uses the `engine`** to communicate with the database. -### Create a `Base` class +We will create a FastAPI **dependency** with `yield` that will provide a new `Session` for each request. This is what ensures that we use a single session per request. 🤓 -Now we will use the function `declarative_base()` that returns a class. +Then we create an `Annotated` dependency `SessionDep` to simplify the rest of the code that will use this dependency. -Later we will inherit from this class to create each of the database models or classes (the ORM models): +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +### Create Database Tables on Startup -## Create the database models +We will create the database tables when the application starts. -Let's now see the file `sql_app/models.py`. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} -### Create SQLAlchemy models from the `Base` class +Here we create the tables on an application startup event. -We will use this `Base` class we created before to create the SQLAlchemy models. +For production you would probably use a migration script that runs before you start your app. 🤓 /// tip -SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. - -But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. +SQLModel will have migration utilities wrapping Alembic, but for now, you can use Alembic directly. /// -Import `Base` from `database` (the file `database.py` from above). - -Create classes that inherit from it. - -These classes are the SQLAlchemy models. - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models. - -### Create model attributes/columns - -Now create all the model (class) attributes. - -Each of these attributes represents a column in its corresponding database table. +### Create a Hero -We use `Column` from SQLAlchemy as the default value. +Because each SQLModel model is also a Pydantic model, you can use it in the same **type annotations** that you could use Pydantic models. -And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument. +For example, if you declare a parameter of type `Hero`, it will be read from the **JSON body**. -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### Create the relationships - -Now create the relationships. - -For this, we use `relationship` provided by SQLAlchemy ORM. - -This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one. +The same way, you can declare it as the function's **return type**, and then the shape of the data will show up in the automatic API docs UI. -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} -When you access `my_user.items`, SQLAlchemy will actually go and fetch the items from the database in the `items` table and populate them here. + -And when accessing the attribute `owner` in an `Item`, it will contain a `User` SQLAlchemy model from the `users` table. It will use the `owner_id` attribute/column with its foreign key to know which record to get from the `users` table. +Here we use the `SessionDep` dependency (a `Session`) to add the new `Hero` to the `Session` instance, commit the changes to the database, refresh the data in the `hero`, and then return it. -## Create the Pydantic models +### Read Heroes -Now let's check the file `sql_app/schemas.py`. +We can **read** `Hero`s from the database using a `select()`. We can include a `limit` and `offset` to paginate the results. -/// tip +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} -To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. +### Read One Hero -These Pydantic models define more or less a "schema" (a valid data shape). +We can **read** a single `Hero`. -So this will help us avoiding confusion while using both. - -/// +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} -### Create initial Pydantic *models* / schemas +### Delete a Hero -Create an `ItemBase` and `UserBase` Pydantic *models* (or let's say "schemas") to have common attributes while creating or reading data. +We can also **delete** a `Hero`. -And create an `ItemCreate` and `UserCreate` that inherit from them (so they will have the same attributes), plus any additional data (attributes) needed for creation. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} -So, the user will also have a `password` when creating it. +### Run the App -But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user. +You can run the app: -//// tab | Python 3.10+ - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -#### SQLAlchemy style and Pydantic style - -Notice that SQLAlchemy *models* define attributes using `=`, and pass the type as a parameter to `Column`, like in: - -```Python -name = Column(String) -``` +
-while Pydantic *models* declare the types using `:`, the new type annotation syntax/type hints: +```console +$ fastapi dev main.py -```Python -name: str +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -Keep these in mind, so you don't get confused when using `=` and `:` with them. - -### Create Pydantic *models* / schemas for reading / returning - -Now create Pydantic *models* (schemas) that will be used when reading data, when returning it from the API. - -For example, before creating an item, we don't know what will be the ID assigned to it, but when reading it (when returning it from the API) we will already know its ID. +
-The same way, when reading a user, we can now declare that `items` will contain the items that belong to this user. +Then go to the `/docs` UI, you will see that **FastAPI** is using these **models** to **document** the API, and it will use them to **serialize** and **validate** the data too. -Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`. +
+ +
-//// tab | Python 3.10+ +## Update the App with Multiple Models -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` +Now let's **refactor** this app a bit to increase **security** and **versatility**. -//// +If you check the previous app, in the UI you can see that, up to now, it lets the client decide the `id` of the `Hero` to create. 😱 -//// tab | Python 3.9+ +We shouldn't let that happen, they could overwrite an `id` we already have assigned in the DB. Deciding the `id` should be done by the **backend** or the **database**, **not by the client**. -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` +Additionally, we create a `secret_name` for the hero, but so far, we are returning it everywhere, that's not very **secret**... 😅 -//// +We'll fix these things by adding a few **extra models**. Here's where SQLModel will shine. ✨ -//// tab | Python 3.8+ +### Create Multiple Models -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` +In **SQLModel**, any model class that has `table=True` is a **table model**. -//// +And any model class that doesn't have `table=True` is a **data model**, these ones are actually just Pydantic models (with a couple of small extra features). 🤓 -/// tip +With SQLModel, we can use **inheritance** to **avoid duplicating** all the fields in all the cases. -Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. +#### `HeroBase` - the base class -/// +Let's start with a `HeroBase` model that has all the **fields that are shared** by all the models: -### Use Pydantic's `orm_mode` +* `name` +* `age` -Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} -This `Config` class is used to provide configurations to Pydantic. +#### `Hero` - the *table model* -In the `Config` class, set the attribute `orm_mode = True`. +Then let's create `Hero`, the actual *table model*, with the **extra fields** that are not always in the other models: -//// tab | Python 3.10+ +* `id` +* `secret_name` -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` +Because `Hero` inherits form `HeroBase`, it **also** has the **fields** declared in `HeroBase`, so all the fields for `Hero` are: -//// +* `id` +* `name` +* `age` +* `secret_name` -//// tab | Python 3.9+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` +#### `HeroPublic` - the public *data model* -//// +Next, we create a `HeroPublic` model, this is the one that will be **returned** to the clients of the API. -//// tab | Python 3.8+ +It has the same fields as `HeroBase`, so it won't include `secret_name`. -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` +Finally, the identity of our heroes is protected! 🥷 -//// +It also re-declares `id: int`. By doing this, we are making a **contract** with the API clients, so that they can always expect the `id` to be there and to be an `int` (it will never be `None`). /// tip -Notice it's assigning a value with `=`, like: - -`orm_mode = True` +Having the return model ensure that a value is always available and always `int` (not `None`) is very useful for the API clients, they can write much simpler code having this certainty. -It doesn't use `:` as for the type declarations before. - -This is setting a config value, not declaring a type. +Also, **automatically generated clients** will have simpler interfaces, so that the developers communicating with your API can have a much better time working with your API. 😎 /// -Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes). - -This way, instead of only trying to get the `id` value from a `dict`, as in: - -```Python -id = data["id"] -``` - -it will also try to get it from an attribute, as in: - -```Python -id = data.id -``` +All the fields in `HeroPublic` are the same as in `HeroBase`, with `id` declared as `int` (not `None`): -And with this, the Pydantic *model* is compatible with ORMs, and you can just declare it in the `response_model` argument in your *path operations*. +* `id` +* `name` +* `age` +* `secret_name` -You will be able to return a database model and it will read the data from it. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} -#### Technical Details about ORM mode +#### `HeroCreate` - the *data model* to create a hero -SQLAlchemy and many others are by default "lazy loading". +Now we create a `HeroCreate` model, this is the one that will **validate** the data from the clients. -That means, for example, that they don't fetch the data for relationships from the database unless you try to access the attribute that would contain that data. +It has the same fields as `HeroBase`, and it also has `secret_name`. -For example, accessing the attribute `items`: - -```Python -current_user.items -``` - -would make SQLAlchemy go to the `items` table and get the items for this user, but not before. - -Without `orm_mode`, if you returned a SQLAlchemy model from your *path operation*, it wouldn't include the relationship data. - -Even if you declared those relationships in your Pydantic models. - -But with ORM mode, as Pydantic itself will try to access the data it needs from attributes (instead of assuming a `dict`), you can declare the specific data you want to return and it will be able to go and get it, even from ORMs. - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -In this file we will have reusable functions to interact with the data in the database. - -**CRUD** comes from: **C**reate, **R**ead, **U**pdate, and **D**elete. - -...although in this example we are only creating and reading. - -### Read data - -Import `Session` from `sqlalchemy.orm`, this will allow you to declare the type of the `db` parameters and have better type checks and completion in your functions. - -Import `models` (the SQLAlchemy models) and `schemas` (the Pydantic *models* / schemas). - -Create utility functions to: - -* Read a single user by ID and by email. -* Read multiple users. -* Read multiple items. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` +Now, when the clients **create a new hero**, they will send the `secret_name`, it will be stored in the database, but those secret names won't be returned in the API to the clients. /// tip -By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add unit tests for them. - -/// +This is how you would handle **passwords**. Receive them, but don't return them in the API. -### Create data - -Now create utility functions to create data. - -The steps are: - -* Create a SQLAlchemy model *instance* with your data. -* `add` that instance object to your database session. -* `commit` the changes to the database (so that they are saved). -* `refresh` your instance (so that it contains any new data from the database, like the generated ID). - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// info - -In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - -The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +You would also **hash** the values of the passwords before storing them, **never store them in plain text**. /// -/// tip +The fields of `HeroCreate` are: -The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. +* `name` +* `age` +* `secret_name` -But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} -And then pass the `hashed_password` argument with the value to save. +#### `HeroUpdate` - the *data model* to update a hero -/// +We didn't have a way to **update a hero** in the previous version of the app, but now with **multiple models**, we can do it. 🎉 -/// warning +The `HeroUpdate` *data model* is somewhat special, it has **all the same fields** that would be needed to create a new hero, but all the fields are **optional** (they all have a default value). This way, when you update a hero, you can send just the fields that you want to update. -This example is not secure, the password is not hashed. +Because all the **fields actually change** (the type now includes `None` and they now have a default value of `None`), we need to **re-declare** them. -In a real life application you would need to hash the password and never save them in plaintext. +We don't really need to inherit from `HeroBase` because we are re-declaring all the fields. I'll leave it inheriting just for consistency, but this is not necessary. It's more a matter of personal taste. 🤷 -For more details, go back to the Security section in the tutorial. +The fields of `HeroUpdate` are: -Here we are focusing only on the tools and mechanics of databases. +* `name` +* `age` +* `secret_name` -/// - -/// tip - -Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: - -`item.dict()` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} -and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: +### Create with `HeroCreate` and return a `HeroPublic` -`Item(**item.dict())` - -And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: - -`Item(**item.dict(), owner_id=user_id)` - -/// +Now that we have **multiple models**, we can update the parts of the app that use them. -## Main **FastAPI** app +We receive in the request a `HeroCreate` *data model*, and from it, we create a `Hero` *table model*. -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. +This new *table model* `Hero` will have the fields sent by the client, and will also have an `id` generated by the database. -### Create the database tables +Then we return the same *table model* `Hero` as is from the function. But as we declare the `response_model` with the `HeroPublic` *data model*, **FastAPI** will use `HeroPublic` to validate and serialize the data. -In a very simplistic way create the database tables: - -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -#### Alembic Note - -Normally you would probably initialize your database (create tables, etc) with Alembic. - -And you would also use Alembic for "migrations" (that's its main job). - -A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. - -You can find an example of Alembic in a FastAPI project in the [Full Stack FastAPI Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. - -### Create a dependency - -Now use the `SessionLocal` class we created in the `sql_app/database.py` file to create a dependency. - -We need to have an independent database session/connection (`SessionLocal`) per request, use the same session through all the request and then close it after the request is finished. - -And then a new session will be created for the next request. - -For that, we will create a new dependency with `yield`, as explained before in the section about [Dependencies with `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished. - -//// tab | Python 3.9+ - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info - -We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - -And then we close it in the `finally` block. - -This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - -But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} - -/// - -And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy. - -This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`: - -//// tab | Python 3.9+ - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info | "Technical Details" - -The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. - -But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. - -/// - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -//// tab | Python 3.9+ - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards. - -And then we can create the required dependency in the *path operation function*, to get that session directly. - -With that, we can just call `crud.get_user` directly from inside of the *path operation function* and use that session. - -/// tip - -Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. - -But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. - -/// +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} /// tip -Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. - -But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. - -/// - -### About `def` vs `async def` - -Here we are using SQLAlchemy code inside of the *path operation function* and in the dependency, and, in turn, it will go and communicate with an external database. - -That could potentially require some "waiting". - -But as SQLAlchemy doesn't have compatibility for using `await` directly, as would be with something like: - -```Python -user = await db.query(User).first() -``` - -...and instead we are using: - -```Python -user = db.query(User).first() -``` - -Then we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info +Now we use `response_model=HeroPublic` instead of the **return type annotation** `-> HeroPublic` because the value that we are returning is actually *not* a `HeroPublic`. -If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. +If we had declared `-> HeroPublic`, your editor and linter would complain (rightfully so) that you are returning a `Hero` instead of a `HeroPublic`. -/// - -/// note | "Very Technical Details" - -If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. +By declaring it in `response_model` we are telling **FastAPI** to do its thing, without interfering with the type annotations and the help from your editor and other tools. /// -## Migrations - -Because we are using SQLAlchemy directly and we don't require any kind of plug-in for it to work with **FastAPI**, we could integrate database migrations with Alembic directly. - -And as the code related to SQLAlchemy and the SQLAlchemy models lives in separate independent files, you would even be able to perform the migrations with Alembic without having to install FastAPI, Pydantic, or anything else. - -The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**. - -For example, in a background task worker with Celery, RQ, or ARQ. - -## Review all the files - - Remember you should have a directory named `my_super_project` that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: +### Read Heroes with `HeroPublic` -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// +We can do the same as before to **read** `Hero`s, again, we use `response_model=list[HeroPublic]` to ensure that the data is validated and serialized correctly. -//// tab | Python 3.8+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` +### Read One Hero with `HeroPublic` -* `sql_app/main.py`: +We can **read** a single hero: -//// tab | Python 3.9+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` +### Update a Hero with `HeroUpdate` -//// +We can **update a hero**. For this we use an HTTP `PATCH` operation. -//// tab | Python 3.8+ +And in the code, we get a `dict` with all the data sent by the client, **only the data sent by the client**, excluding any values that would be there just for being the default values. To do it we use `exclude_unset=True`. This is the main trick. 🪄 -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` +Then we use `hero_db.sqlmodel_update(hero_data)` to update the `hero_db` with the data from `hero_data`. -//// +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} -## Check it +### Delete a Hero Again -You can copy this code and use it as is. +**Deleting** a hero stays pretty much the same. -/// info +We won't satisfy the desire to refactor everything in this one. 😅 -In fact, the code shown here is part of the tests. As most of the code in these docs. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} -/// - -Then you can run it with Uvicorn: +### Run the App Again +You can run the app again:
```console -$ uvicorn sql_app.main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```
-And then, you can open your browser at http://127.0.0.1:8000/docs. - -And you will be able to interact with your **FastAPI** application, reading data from a real database: - - - -## Interact with the database directly - -If you want to explore the SQLite database (file) directly, independently of FastAPI, to debug its contents, add tables, columns, records, modify data, etc. you can use DB Browser for SQLite. - -It will look like this: +If you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc. +
+
-You can also use an online SQLite browser like SQLite Viewer or ExtendsClass. - -## Alternative DB session with middleware - -If you can't use dependencies with `yield` -- for example, if you are not using **Python 3.7** and can't install the "backports" mentioned above for **Python 3.6** -- you can set up the session in a "middleware" in a similar way. - -A "middleware" is basically a function that is always executed for each request, with some code executed before, and some code executed after the endpoint function. - -### Create a middleware - -The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished. - -//// tab | Python 3.9+ - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -/// info - -We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - -And then we close it in the `finally` block. - -This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - -/// - -### About `request.state` - -`request.state` is a property of each `Request` object. It is there to store arbitrary objects attached to the request itself, like the database session in this case. You can read more about it in Starlette's docs about `Request` state. - -For us in this case, it helps us ensure a single database session is used through all the request, and then closed afterwards (in the middleware). - -### Dependencies with `yield` or middleware - -Adding a **middleware** here is similar to what a dependency with `yield` does, with some differences: - -* It requires more code and is a bit more complex. -* The middleware has to be an `async` function. - * If there is code in it that has to "wait" for the network, it could "block" your application there and degrade performance a bit. - * Although it's probably not very problematic here with the way `SQLAlchemy` works. - * But if you added more code to the middleware that had a lot of I/O waiting, it could then be problematic. -* A middleware is run for *every* request. - * So, a connection will be created for every request. - * Even when the *path operation* that handles that request didn't need the DB. - -/// tip - -It's probably better to use dependencies with `yield` when they are enough for the use case. - -/// - -/// info - -Dependencies with `yield` were added recently to **FastAPI**. +## Recap -A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. +You can use **SQLModel** to interact with a SQL database and simplify the code with *data models* and *table models*. -/// +You can learn a lot more at the **SQLModel** docs, there's a longer mini tutorial on using SQLModel with **FastAPI**. 🚀 diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index e55c6f176..8e0f6765d 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -71,13 +71,11 @@ plugins: redirects: redirect_maps: deployment/deta.md: deployment/cloud.md - advanced/sql-databases-peewee.md: how-to/sql-databases-peewee.md - advanced/async-sql-databases.md: how-to/async-sql-encode-databases.md - advanced/nosql-databases.md: how-to/nosql-databases-couchbase.md advanced/graphql.md: how-to/graphql.md advanced/custom-request-and-route.md: how-to/custom-request-and-route.md advanced/conditional-openapi.md: how-to/conditional-openapi.md advanced/extending-openapi.md: how-to/extending-openapi.md + advanced/testing-database.md: how-to/testing-database.md mkdocstrings: handlers: python: @@ -187,7 +185,6 @@ nav: - advanced/testing-websockets.md - advanced/testing-events.md - advanced/testing-dependencies.md - - advanced/testing-database.md - advanced/async-tests.md - advanced/settings.md - advanced/openapi-callbacks.md @@ -214,9 +211,7 @@ nav: - how-to/separate-openapi-schemas.md - how-to/custom-docs-ui-assets.md - how-to/configure-swagger-ui.md - - how-to/sql-databases-peewee.md - - how-to/async-sql-encode-databases.md - - how-to/nosql-databases-couchbase.md + - how-to/testing-database.md - Reference (Code API): - reference/index.md - reference/fastapi.md diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md deleted file mode 100644 index ecab4f65b..000000000 --- a/docs/zh/docs/advanced/testing-database.md +++ /dev/null @@ -1,101 +0,0 @@ -# 测试数据库 - -您还可以使用[测试依赖项](testing-dependencies.md){.internal-link target=_blank}中的覆盖依赖项方法变更测试的数据库。 - -实现设置其它测试数据库、在测试后回滚数据、或预填测试数据等操作。 - -本章的主要思路与上一章完全相同。 - -## 为 SQL 应用添加测试 - -为了使用测试数据库,我们要升级 [SQL 关系型数据库](../tutorial/sql-databases.md){.internal-link target=_blank} 一章中的示例。 - -应用的所有代码都一样,直接查看那一章的示例代码即可。 - -本章只是新添加了测试文件。 - -正常的依赖项 `get_db()` 返回数据库会话。 - -测试时使用覆盖依赖项返回自定义数据库会话代替正常的依赖项。 - -本例中,要创建仅用于测试的临时数据库。 - -## 文件架构 - -创建新文件 `sql_app/tests/test_sql_app.py`。 - -因此,新的文件架构如下: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## 创建新的数据库会话 - -首先,为新建数据库创建新的数据库会话。 - -测试时,使用 `test.db` 替代 `sql_app.db`。 - -但其余的会话代码基本上都是一样的,只要复制就可以了。 - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip | "提示" - -为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 - -为了把注意力集中在测试代码上,本例只是复制了这段代码。 - -/// - -## 创建数据库 - -因为现在是想在新文件中使用新数据库,所以要使用以下代码创建数据库: - -```Python -Base.metadata.create_all(bind=engine) -``` - -一般是在 `main.py` 中调用这行代码,但在 `main.py` 里,这行代码用于创建 `sql_app.db`,但是现在要为测试创建 `test.db`。 - -因此,要在测试代码中添加这行代码创建新的数据库文件。 - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 覆盖依赖项 - -接下来,创建覆盖依赖项,并为应用添加覆盖内容。 - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip | "提示" - -`overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 - -/// - -## 测试应用 - -然后,就可以正常测试了。 - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs_src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py deleted file mode 100644 index cbf43d790..000000000 --- a/docs_src/async_sql_databases/tutorial001.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import List - -import databases -import sqlalchemy -from fastapi import FastAPI -from pydantic import BaseModel - -# SQLAlchemy specific code, as with any other app -DATABASE_URL = "sqlite:///./test.db" -# DATABASE_URL = "postgresql://user:password@postgresserver/db" - -database = databases.Database(DATABASE_URL) - -metadata = sqlalchemy.MetaData() - -notes = sqlalchemy.Table( - "notes", - metadata, - sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), - sqlalchemy.Column("text", sqlalchemy.String), - sqlalchemy.Column("completed", sqlalchemy.Boolean), -) - - -engine = sqlalchemy.create_engine( - DATABASE_URL, connect_args={"check_same_thread": False} -) -metadata.create_all(engine) - - -class NoteIn(BaseModel): - text: str - completed: bool - - -class Note(BaseModel): - id: int - text: str - completed: bool - - -app = FastAPI() - - -@app.on_event("startup") -async def startup(): - await database.connect() - - -@app.on_event("shutdown") -async def shutdown(): - await database.disconnect() - - -@app.get("/notes/", response_model=List[Note]) -async def read_notes(): - query = notes.select() - return await database.fetch_all(query) - - -@app.post("/notes/", response_model=Note) -async def create_note(note: NoteIn): - query = notes.insert().values(text=note.text, completed=note.completed) - last_record_id = await database.execute(query) - return {**note.dict(), "id": last_record_id} diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py deleted file mode 100644 index 91893e528..000000000 --- a/docs_src/nosql_databases/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from couchbase import LOCKMODE_WAIT -from couchbase.bucket import Bucket -from couchbase.cluster import Cluster, PasswordAuthenticator -from fastapi import FastAPI -from pydantic import BaseModel - -USERPROFILE_DOC_TYPE = "userprofile" - - -def get_bucket(): - cluster = Cluster( - "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" - ) - authenticator = PasswordAuthenticator("username", "password") - cluster.authenticate(authenticator) - bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) - bucket.timeout = 30 - bucket.n1ql_timeout = 300 - return bucket - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - type: str = USERPROFILE_DOC_TYPE - hashed_password: str - - -def get_user(bucket: Bucket, username: str): - doc_id = f"userprofile::{username}" - result = bucket.get(doc_id, quiet=True) - if not result.value: - return None - user = UserInDB(**result.value) - return user - - -# FastAPI specific code -app = FastAPI() - - -@app.get("/users/{username}", response_model=User) -def read_user(username: str): - bucket = get_bucket() - user = get_user(bucket=bucket, username=username) - return user diff --git a/docs_src/sql_databases/sql_app/__init__.py b/docs_src/sql_databases/sql_app/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py deleted file mode 100644 index f7206bcb4..000000000 --- a/docs_src/sql_databases/sql_app/alt_main.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py deleted file mode 100644 index e7508c59d..000000000 --- a/docs_src/sql_databases/sql_app/main.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py deleted file mode 100644 index c49beba88..000000000 --- a/docs_src/sql_databases/sql_app/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List, Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app/tests/__init__.py b/docs_src/sql_databases/sql_app/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py deleted file mode 100644 index 5f55add0a..000000000 --- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py +++ /dev/null @@ -1,50 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite://" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, - connect_args={"check_same_thread": False}, - poolclass=StaticPool, -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py310/__init__.py b/docs_src/sql_databases/sql_app_py310/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py310/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py310/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py310/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py310/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py deleted file mode 100644 index aea2e3f10..000000000 --- a/docs_src/sql_databases/sql_app_py310/schemas.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: str | None = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py310/tests/__init__.py b/docs_src/sql_databases/sql_app_py310/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py39/__init__.py b/docs_src/sql_databases/sql_app_py39/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py39/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py39/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py39/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py39/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py deleted file mode 100644 index dadc403d9..000000000 --- a/docs_src/sql_databases/sql_app_py39/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/sql_databases/sql_app_py39/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py new file mode 100644 index 000000000..be86ec0ee --- /dev/null +++ b/docs_src/sql_databases/tutorial001.py @@ -0,0 +1,71 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py new file mode 100644 index 000000000..8c000d31c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an.py @@ -0,0 +1,74 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py new file mode 100644 index 000000000..de1fb81fa --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py310.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py39.py b/docs_src/sql_databases/tutorial001_an_py39.py new file mode 100644 index 000000000..595892746 --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py39.py @@ -0,0 +1,73 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py new file mode 100644 index 000000000..b58462e6a --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py310.py @@ -0,0 +1,69 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py39.py b/docs_src/sql_databases/tutorial001_py39.py new file mode 100644 index 000000000..410a52d0c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py39.py @@ -0,0 +1,71 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py new file mode 100644 index 000000000..4350d19c6 --- /dev/null +++ b/docs_src/sql_databases/tutorial002.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py new file mode 100644 index 000000000..15e3d7c3a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py new file mode 100644 index 000000000..64c554b8a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py310.py @@ -0,0 +1,103 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py39.py b/docs_src/sql_databases/tutorial002_an_py39.py new file mode 100644 index 000000000..a8a0721ff --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py39.py @@ -0,0 +1,103 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py new file mode 100644 index 000000000..ec3d68db5 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py310.py @@ -0,0 +1,102 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py39.py b/docs_src/sql_databases/tutorial002_py39.py new file mode 100644 index 000000000..d8f5dd090 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py39.py @@ -0,0 +1,104 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/requirements-docs.txt b/requirements-docs.txt index c05bd51e3..1639159af 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -16,4 +16,4 @@ griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 -markdown-include-variants==0.0.1 +markdown-include-variants==0.0.3 diff --git a/requirements-tests.txt b/requirements-tests.txt index 7b1f7ea1a..189fcaf7e 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -4,10 +4,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 dirty-equals ==0.6.0 -# TODO: once removing databases from tutorial, upgrade SQLAlchemy -# probably when including SQLModel -sqlalchemy >=1.3.18,<2.0.33 -databases[sqlite] >=0.3.2,<0.7.0 +sqlmodel==0.0.22 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 diff --git a/scripts/playwright/sql_databases/image01.py b/scripts/playwright/sql_databases/image01.py new file mode 100644 index 000000000..0dd6f2514 --- /dev/null +++ b/scripts/playwright/sql_databases/image01.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial001.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/sql_databases/image02.py b/scripts/playwright/sql_databases/image02.py new file mode 100644 index 000000000..6c4f685e8 --- /dev/null +++ b/scripts/playwright/sql_databases/image02.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial002.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/tests/test_tutorial/test_async_sql_databases/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py deleted file mode 100644 index 13568a532..000000000 --- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py +++ /dev/null @@ -1,146 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(name="app", scope="module") -def get_app(): - with pytest.warns(DeprecationWarning): - from docs_src.async_sql_databases.tutorial001 import app - yield app - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_read(app: FastAPI): - with TestClient(app) as client: - note = {"text": "Foo bar", "completed": False} - response = client.post("/notes/", json=note) - assert response.status_code == 200, response.text - data = response.json() - assert data["text"] == note["text"] - assert data["completed"] == note["completed"] - assert "id" in data - response = client.get("/notes/") - assert response.status_code == 200, response.text - assert data in response.json() - - -def test_openapi_schema(app: FastAPI): - with TestClient(app) as client: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/notes/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Notes Notes Get", - "type": "array", - "items": { - "$ref": "#/components/schemas/Note" - }, - } - } - }, - } - }, - "summary": "Read Notes", - "operationId": "read_notes_notes__get", - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Note"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Note", - "operationId": "create_note_notes__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/NoteIn"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "NoteIn": { - "title": "NoteIn", - "required": ["text", "completed"], - "type": "object", - "properties": { - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "Note": { - "title": "Note", - "required": ["id", "text", "completed"], - "type": "object", - "properties": { - "id": {"title": "Id", "type": "integer"}, - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": { - "$ref": "#/components/schemas/ValidationError" - }, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py deleted file mode 100644 index e3e2b36a8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ /dev/null @@ -1,419 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py deleted file mode 100644 index 73b97e09d..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ /dev/null @@ -1,421 +0,0 @@ -import importlib -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(): - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py deleted file mode 100644 index a078f012a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py deleted file mode 100644 index a5da07ac6..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py deleted file mode 100644 index 5a9106598..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py deleted file mode 100644 index a354ba905..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py deleted file mode 100644 index ce6ce230c..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py +++ /dev/null @@ -1,27 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_pydanticv1 - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py deleted file mode 100644 index 545d63c2a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py310, needs_pydanticv1 - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py deleted file mode 100644 index 99bfd3fa8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py39, needs_pydanticv1 - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py new file mode 100644 index 000000000..cc7e590df --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py @@ -0,0 +1,373 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 999, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"} + ) + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Dead Pond", + "age": 30, + "id": IsInt(), + "secret_name": "Dive Wilson", + }, + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + }, + { + "name": "Rusty-Man", + "age": None, + "id": IsInt(), + "secret_name": "Tommy Sharp", + }, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + } + ] + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hero" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Hero": { + "properties": { + "id": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Id", + } + ), + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "Hero", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py new file mode 100644 index 000000000..68c1966f5 --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -0,0 +1,481 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 9000, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "id": IsInt(), "name": "Dead Pond"} + ) + assert ( + response.json()["id"] != 9000 + ), "The ID should be generated by the database" + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": IsInt()} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + {"name": "Dead Pond", "age": 30, "id": IsInt()}, + {"name": "Spider-Boy", "age": 18, "id": IsInt()}, + {"name": "Rusty-Man", "age": None, "id": IsInt()}, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [{"name": "Spider-Boy", "age": 18, "id": IsInt()}] + ) + + # Update a hero + response = client.patch( + f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None} + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Get updated hero + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + # The hero is no longer found + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + # Delete a hero that does not exist + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + # Update a hero that does not exist + response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"}) + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroCreate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HeroPublic" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "patch": { + "summary": "Update Hero", + "operationId": "update_hero_heroes__hero_id__patch", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroUpdate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "HeroCreate": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "HeroCreate", + }, + "HeroPublic": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "id": {"type": "integer", "title": "Id"}, + }, + "type": "object", + "required": ["name", "id"], + "title": "HeroPublic", + }, + "HeroUpdate": { + "properties": { + "name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Name", + } + ), + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Secret Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Secret Name", + } + ), + }, + "type": "object", + "title": "HeroUpdate", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) From dbb4a91e121317da6e53e1c06aa02170c40cf78c Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 9 Oct 2024 19:45:08 +0000 Subject: [PATCH 344/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e34fd0df9..819d4b327 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* ✨ Add new tutorial for SQL databases with SQLModel. PR [#12285](https://github.com/fastapi/fastapi/pull/12285) by [@tiangolo](https://github.com/tiangolo). * 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol). * 🔧 Remove `base_path` for `mdx_include` Markdown extension in MkDocs. PR [#12391](https://github.com/fastapi/fastapi/pull/12391) by [@tiangolo](https://github.com/tiangolo). * 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu). From 104dc0b8d86cb57165da919bc8cec2e225f6b61c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:11:46 +0200 Subject: [PATCH 345/356] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12396)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.6.0 → v5.0.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.6.0...v5.0.0) - [github.com/astral-sh/ruff-pre-commit: v0.6.8 → v0.6.9](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.8...v0.6.9) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 48a7d495c..a62acccfe 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 + rev: v5.0.0 hooks: - id: check-added-large-files - id: check-toml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.8 + rev: v0.6.9 hooks: - id: ruff args: From 529155e72e196f82e0289f173a185e8ddb2888ce Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 9 Oct 2024 20:12:15 +0000 Subject: [PATCH 346/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 819d4b327..4fe600ed4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -40,6 +40,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12396](https://github.com/fastapi/fastapi/pull/12396) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). From 8ae4603d680f86ae1e5f96e58546dee4f543171f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Pacheco?= Date: Sat, 12 Oct 2024 05:36:32 -0400 Subject: [PATCH 347/356] =?UTF-8?q?=F0=9F=90=9B=20Remove=20`Required`=20sh?= =?UTF-8?q?adowing=20from=20fastapi=20using=20Pydantic=20v2=20(#12197)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- .../query_params_str_validations/tutorial006d.py | 3 +-- .../tutorial006d_an.py | 3 +-- .../tutorial006d_an_py39.py | 3 +-- fastapi/_compat.py | 9 +++++---- fastapi/dependencies/utils.py | 14 ++++++++------ 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py index 42c5bf4eb..a8d69c889 100644 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ b/docs_src/query_params_str_validations/tutorial006d.py @@ -1,11 +1,10 @@ from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: str = Query(default=Required, min_length=3)): +async def read_items(q: str = Query(default=..., min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py index bc8283e15..ea3b02583 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ b/docs_src/query_params_str_validations/tutorial006d_an.py @@ -1,12 +1,11 @@ from fastapi import FastAPI, Query -from pydantic import Required from typing_extensions import Annotated app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py index 035d9e3bd..687a9f544 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006d_an_py39.py @@ -1,13 +1,12 @@ from typing import Annotated from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 4b07b44fa..56c5d744e 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -71,7 +71,7 @@ if PYDANTIC_V2: general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 ) - Required = PydanticUndefined + RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient @@ -313,9 +313,10 @@ else: 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 - ) + + # Keeping old "Required" functionality from Pydantic V1, without + # shadowing typing.Required. + RequiredParam: Any = Ellipsis # type: ignore[no-redef] from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 813c74620..87653c80d 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -24,7 +24,7 @@ from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, - Required, + RequiredParam, Undefined, _regenerate_error_with_loc, copy_field_info, @@ -377,7 +377,9 @@ def analyze_param( field_info = copy_field_info( field_info=fastapi_annotation, annotation=use_annotation ) - assert field_info.default is Undefined or field_info.default is Required, ( + assert ( + field_info.default is Undefined or field_info.default is RequiredParam + ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) @@ -385,7 +387,7 @@ def analyze_param( assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: - field_info.default = Required + field_info.default = RequiredParam # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation @@ -434,9 +436,9 @@ def analyze_param( ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: - default_value = value if value is not inspect.Signature.empty else Required + default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: - # We might check here that `default_value is Required`, but the fact is that the same + # We might check here that `default_value is RequiredParam`, 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=use_annotation) @@ -480,7 +482,7 @@ def analyze_param( type_=use_annotation_from_field_info, default=field_info.default, alias=alias, - required=field_info.default in (Required, Undefined), + required=field_info.default in (RequiredParam, Undefined), field_info=field_info, ) if is_path_param: From b29cf1621a9b9046ff68cf21c67f96953bc8feeb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:36:55 +0000 Subject: [PATCH 348/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4fe600ed4..d070a84a3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise). + ### Refactors * ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo). From e049fc4ea15a7b844326efa545a7e370713f6612 Mon Sep 17 00:00:00 2001 From: Felix Fanghaenel <35657654+flxdot@users.noreply.github.com> Date: Sat, 12 Oct 2024 11:44:57 +0200 Subject: [PATCH 349/356] =?UTF-8?q?=F0=9F=90=9B=20Fix=20openapi=20generati?= =?UTF-8?q?on=20with=20responses=20kwarg=20(#10895)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: flxdot Co-authored-by: Sofie Van Landeghem Co-authored-by: Sławek Ehlert --- fastapi/routing.py | 4 ++- tests/test_computed_fields.py | 27 ++++++++++++-- ...t_openapi_separate_input_output_schemas.py | 36 ++++++++++++++++--- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 86e303602..8ea4bb219 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -541,7 +541,9 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_model_field(name=response_name, type_=model) + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py index 5286507b2..a1b412168 100644 --- a/tests/test_computed_fields.py +++ b/tests/test_computed_fields.py @@ -24,13 +24,18 @@ def get_client(): def read_root() -> Rectangle: return Rectangle(width=3, length=4) + @app.get("/responses", responses={200: {"model": Rectangle}}) + def read_responses() -> Rectangle: + return Rectangle(width=3, length=4) + client = TestClient(app) return client +@pytest.mark.parametrize("path", ["/", "/responses"]) @needs_pydanticv2 -def test_get(client: TestClient): - response = client.get("/") +def test_get(client: TestClient, path: str): + response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"width": 3, "length": 4, "area": 12} @@ -58,7 +63,23 @@ def test_openapi_schema(client: TestClient): } }, } - } + }, + "/responses": { + "get": { + "summary": "Read Responses", + "operationId": "read_responses_responses_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Rectangle"} + } + }, + } + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py index aeb85f735..f7e045259 100644 --- a/tests/test_openapi_separate_input_output_schemas.py +++ b/tests/test_openapi_separate_input_output_schemas.py @@ -26,8 +26,8 @@ class Item(BaseModel): def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) - @app.post("/items/") - def create_item(item: Item): + @app.post("/items/", responses={402: {"model": Item}}) + def create_item(item: Item) -> Item: return item @app.post("/items-list/") @@ -174,7 +174,23 @@ def test_openapi_schema(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, }, "422": { "description": "Validation Error", @@ -374,7 +390,19 @@ def test_openapi_schema_no_separate(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, }, "422": { "description": "Validation Error", From f0be7686468229a7c9aa49c0c2cfff754c81dbdc Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:45:17 +0000 Subject: [PATCH 350/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d070a84a3..07035bf94 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Fixes +* 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot). * 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise). ### Refactors From 113da5b0a7f33be300b7fea8dddbe51ee7b96157 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 11:51:09 +0200 Subject: [PATCH 351/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 07035bf94..4843370e7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.1 + ### Fixes * 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 7dd74c28f..09c8074ed 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.115.0" +__version__ = "0.115.1" from starlette import status as status From b77f2351d1561c0e9599205c3faaaed7b52c24fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 11:59:01 +0200 Subject: [PATCH 352/356] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20`>=3D0.37.2,<0.41.0`=20(#12431)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 1be2817a1..c934356d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.37.2,<0.39.0", + "starlette>=0.37.2,<0.41.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From 63c428fbf9363aaad0e967d30f8b199f5dc23e39 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:59:23 +0000 Subject: [PATCH 353/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4843370e7..780f41ed3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.1 ### Fixes From 07684aea793d042fb5a12dde46dfe6d1e2196725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 12:00:47 +0200 Subject: [PATCH 354/356] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 780f41ed3..3ba765b08 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.2 + ### Upgrades * ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 09c8074ed..77b52f35b 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.115.1" +__version__ = "0.115.2" from starlette import status as status From 91672fb9edf4a504a0106b5396f9be16ffbf40b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 12 Oct 2024 12:29:31 +0200 Subject: [PATCH 355/356] =?UTF-8?q?=E2=AC=86=20Update=20httpx=20requiremen?= =?UTF-8?q?t=20from=20<0.25.0,>=3D0.23.0=20to=20>=3D0.23.0,<0.28.0=20(#115?= =?UTF-8?q?09)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates the requirements on [httpx](https://github.com/encode/httpx) to permit the latest version. - [Release notes](https://github.com/encode/httpx/releases) - [Changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) - [Commits](https://github.com/encode/httpx/compare/0.23.0...0.27.0) --- updated-dependencies: - dependency-name: httpx dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index 40b956e51..331d2a5b3 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,4 +1,4 @@ # For mkdocstrings and tests -httpx >=0.23.0,<0.25.0 +httpx >=0.23.0,<0.28.0 # For linting and generating docs versions ruff ==0.6.4 From 3347f0dde58899e9d934b9f25fcd4f0120a002da Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 10:29:52 +0000 Subject: [PATCH 356/356] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3ba765b08..90e45367b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot). + ## 0.115.2 ### Upgrades

$5q*9#iM5)%>&v0gd! zyZF&jUgHLy<$t{|B@!rcCYlN(<8<711<7BNqtlstc+6$|ApFg$(EFe2n>#ZQ^6NTA zV?L3(%3r>UQz_P(y+1mW1C5^@tToj$OF${on>^DdzqnP!F?(zY1NsZ%RoJ{2`ySEJ zs8^8xu4HCGW(0x3&e>;!-qzd~8jF~`iADBMe@nd0sGec<7_8vjyv92G!-`@oJ(bVf z;}GscvNk5QqW4L@y4>S?iod#Aq4cygAQh&GUfM()M%>?-)>(ss1Cx`|e0(QEbB%I& zzvS7lbI}{Ms8gornB3pnI}L}QV=lh#?S&PqWl&O6lkZo^|Ai{4UabUxIh*Uqap<%a z942kMmK{6JKjl6Q&vBQ@a1=e#{PipAt&YQN{TBzLkv_+mSuZ!;s^&RY-zkx8rGXQ=F>fUD!J6n;ce34}ZTO*uP3g>D&8S-Jnu z&rtgJtzsXAgd}!Of0TwhQx4m(zTE^8UMXJ`_-Bd(e zzF=$?3;i-(5dyrX6MIBD!VYkKq|WkqEr$VXfi5iv4}oo|sHycJ=Dg^nV;a#8f`_PI z9qms0 zBCQ#YMP#w=xs1@nkN$(mk^cYiDQoBXkexFaywmFJ>)Y=dFlYoUL_|hj)XbMcp}VVw z_g_BUGc{2$DQ6WH6#k21IsVlGdWEcPS~q7LKZ8LvHQ43> z@s07I{6u%-7S3Iczl`4h@-_Xt{KFXjU!T+J%Iq->$6cHcyGB_1YQP1I7HTsKBZa)io&SCsAuR>FwgZs4OFPeIi`*2Mu>GU*fK3qO8~NV!yTPZws)~md@yk%Wz$Lwx`&z9R5;GII=odPjX^sX^ z;gh=f3*w6|vAq(RPZdnaNOE%nJ{x7p3Mx7bD$%@wwm6!ay?wrE=X)bnW`i-Pt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_{JD*nS)iuVIU(x7CJR230&PWvgZ*S}crD)_VUi zJ4UydzI{4Ga3gQ{78&n8Z1F}}y#*|qCy&a8Kq37^WOv?|43f` zQ~2^B|MjZ}H&;syKk@!^N#MB|aTP-Zjo?t4iZvJZO+|aZY4ecKhf1B1W4RvZu-3D! zC4=RmSZS0t8_PE(&}A3!d|^%$#Zp3LqlEPWtpCyJFUCp4CWgY^^Tn`|{_x^UubRhl zqwJ;~>8=Q~*#%<~xzajgrL@m+9(?9kd@Z>Asdf5eiNsv{>t{3|TtMzy$$IhQ;Ykw% zXz86hW)FEX|4~D%ep0q`fs$ekCuOY%N=`0L0QA#tEJ2?)W;{1zq+-PPLP)-FPlk0yg->8T_d{PrTpG%FI@3>~@gA3MWLG)905p+sL+Dam*#UjBf3rTN*nLhnO zR+?<(RQJ*Kz%I}2i4HW;U**Y%+bl-SJ{PUhP0tI)HlAQA4^v$?$*@pyOR-Ro>laWzV9l0;LavJnDp95ea_22-cTMw8=wBYmlWwe|)Mn2GvoD)5y0Uy{Vv z={JbL(Sa3035D*5$3%ojH$Nxt)hUDFqONRPQn&q0Rhq%~?_Yo&#;cZ8h1NYy7-F=o zny?8Za6VL&R#pl#F$#C>T)rI^Q~@f7{1P)pu)Zku5D{q!z1Dd?c3jh~VJoH{Yuj<5}6S zNqR2_4=R91C)_I)%FVvVN6jh-KyjIA+ko%fnn=2ov@-IKY+-OyrV!&zKbF_ba|Ec5 zG_L>V;KTVM|L&juS*}nOOim4!Ox%gu{`3#b9|L=I$`S9E1H6M@d0l KzDn-xr~eO~3Q%MK diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 7836efae1..972eb9308 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -1,22 +1,18 @@ # SQL (Relational) Databases -/// info +**FastAPI** doesn't require you to use a SQL (relational) database. But you can use **any database** that you want. -These docs are about to be updated. 🎉 +Here we'll see an example using SQLModel. -The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +**SQLModel** is built on top of SQLAlchemy and Pydantic. It was made by the same author of **FastAPI** to be the perfect match for FastAPI applications that need to use **SQL databases**. -The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -/// - -**FastAPI** doesn't require you to use a SQL (relational) database. +/// tip -But you can use any relational database that you want. +You could use any other SQL or NoSQL database library you want (in some cases called "ORMs"), FastAPI doesn't force you to use anything. 😎 -Here we'll see an example using SQLAlchemy. +/// -You can easily adapt it to any database supported by SQLAlchemy, like: +As SQLModel is based on SQLAlchemy, you can easily use **any database supported** by SQLAlchemy (which makes them also supported by SQLModel), like: * PostgreSQL * MySQL @@ -30,891 +26,335 @@ Later, for your production application, you might want to use a database server /// tip -There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. - -The **FastAPI** specific code is as small as always. - -/// - -## ORMs - -**FastAPI** works with any database and any style of library to talk to the database. - -A common pattern is to use an "ORM": an "object-relational mapping" library. - -An ORM has tools to convert ("*map*") between *objects* in code and database tables ("*relations*"). - -With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type. - -For example a class `Pet` could represent a SQL table `pets`. - -And each *instance* object of that class represents a row in the database. - -For example an object `orion_cat` (an instance of `Pet`) could have an attribute `orion_cat.type`, for the column `type`. And the value of that attribute could be, e.g. `"cat"`. - -These ORMs also have tools to make the connections or relations between tables or entities. - -This way, you could also have an attribute `orion_cat.owner` and the owner would contain the data for this pet's owner, taken from the table *owners*. - -So, `orion_cat.owner.name` could be the name (from the `name` column in the `owners` table) of this pet's owner. - -It could have a value like `"Arquilian"`. - -And the ORM will do all the work to get the information from the corresponding table *owners* when you try to access it from your pet object. - -Common ORMs are for example: Django-ORM (part of the Django framework), SQLAlchemy ORM (part of SQLAlchemy, independent of framework) and Peewee (independent of framework), among others. - -Here we will see how to work with **SQLAlchemy ORM**. - -In a similar way you could use any other ORM. - -/// tip - -There's an equivalent article using Peewee here in the docs. +There is an official project generator with **FastAPI** and **PostgreSQL** including a frontend and more tools: https://github.com/fastapi/full-stack-fastapi-template /// -## File structure - -For these examples, let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -The file `__init__.py` is just an empty file, but it tells Python that `sql_app` with all its modules (Python files) is a package. - -Now let's see what each file/module does. - -## Install `SQLAlchemy` +This is a very simple and short tutorial, if you want to learn about databases in general, about SQL, or more advanced features, go to the SQLModel docs. -First you need to install `SQLAlchemy`. +## Install `SQLModel` -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `sqlmodel`: