From 8d928def2e3e5def8b4ffcd01e9c6efc17c10afe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9E=84=EC=84=A0=EC=98=A4?= Date: Mon, 28 Oct 2024 00:01:38 +0900 Subject: [PATCH 01/83] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translation?= =?UTF-8?q?=20for=20`docs/ko/docs/benchmarks.md`=20(#12540)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/benchmarks.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/ko/docs/benchmarks.md diff --git a/docs/ko/docs/benchmarks.md b/docs/ko/docs/benchmarks.md new file mode 100644 index 000000000..aff8ae70e --- /dev/null +++ b/docs/ko/docs/benchmarks.md @@ -0,0 +1,34 @@ +# 벤치마크 + +독립적인 TechEmpower 벤치마크에 따르면 **FastAPI** 애플리케이션이 Uvicorn을 사용하여 가장 빠른 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을 사용하므로 Uvicorn보다 빨라질 수 없는 것과 마찬가지로, **FastAPI**는 Starlette를 사용하므로 더 빠를 수 없습니다. + * FastAPI는 Starlette에 추가적으로 더 많은 기능을 제공합니다. API를 구축할 때 거의 항상 필요한 데이터 검증 및 직렬화와 같은 기능들이 포함되어 있습니다. 그리고 이를 사용하면 문서 자동화 기능도 제공됩니다(문서 자동화는 응용 프로그램 실행 시 오버헤드를 추가하지 않고 시작 시 생성됩니다). + * FastAPI를 사용하지 않고 직접 Starlette(또는 Sanic, Flask, Responder 등)를 사용했다면 데이터 검증 및 직렬화를 직접 구현해야 합니다. 따라서 최종 응용 프로그램은 FastAPI를 사용한 것과 동일한 오버헤드를 가지게 될 것입니다. 많은 경우 데이터 검증 및 직렬화가 응용 프로그램에서 작성된 코드 중 가장 많은 부분을 차지합니다. + * 따라서 FastAPI를 사용함으로써 개발 시간, 버그, 코드 라인을 줄일 수 있으며, FastAPI를 사용하지 않았을 때와 동일하거나 더 나은 성능을 얻을 수 있습니다(코드에서 모두 구현해야 하기 때문에). + * FastAPI를 비교할 때는 Flask-apispec, NestJS, Molten 등 데이터 검증, 직렬화 및 문서화가 통합된 자동 데이터 검증, 직렬화 및 문서화를 제공하는 웹 응용 프로그램 프레임워크(또는 도구 집합)와 비교하세요. From 128c96dc9a9785013206fe878014ebb589fe32da Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:02:00 +0000 Subject: [PATCH 02/83] =?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 d0bb66ee6..757ed7023 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/benchmarks.md`. PR [#12540](https://github.com/fastapi/fastapi/pull/12540) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/separate-openapi-schemas.md`. PR [#12518](https://github.com/fastapi/fastapi/pull/12518) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12521](https://github.com/fastapi/fastapi/pull/12521) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12522](https://github.com/fastapi/fastapi/pull/12522) by [@codingjenny](https://github.com/codingjenny). From 092da9a8a303dc1bc71bc644f75266ff8f94fbe3 Mon Sep 17 00:00:00 2001 From: Philip Okiokio <55271518+philipokiokio@users.noreply.github.com> Date: Sun, 27 Oct 2024 16:15:05 +0100 Subject: [PATCH 03/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/how-to/extending-openapi.md`=20(#12562)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/extending-openapi.md | 30 ++++++++++++------------ 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index 2b0367952..8c7790725 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -43,25 +43,24 @@ For example, let's add Date: Sun, 27 Oct 2024 15:15:30 +0000 Subject: [PATCH 04/83] =?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 757ed7023..d9f5e1b4f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/how-to/extending-openapi.md`. PR [#12562](https://github.com/fastapi/fastapi/pull/12562) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes for `docs/en/docs/how-to/configure-swagger-ui.md`. PR [#12556](https://github.com/fastapi/fastapi/pull/12556) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes for `docs/en/docs/how-to/separate-openapi-schemas.md`. PR [#12555](https://github.com/fastapi/fastapi/pull/12555) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes for `docs/en/docs/advanced/security/http-basic-auth.md`. PR [#12553](https://github.com/fastapi/fastapi/pull/12553) by [@tiangolo](https://github.com/tiangolo). From 50c6f801170ef991bc6df0095932314bf2f67d9a Mon Sep 17 00:00:00 2001 From: Philip Okiokio <55271518+philipokiokio@users.noreply.github.com> Date: Sun, 27 Oct 2024 16:18:53 +0100 Subject: [PATCH 05/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/how-to/graphql.md`=20(#12564)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/graphql.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index 2a4377d16..5d8f879d1 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -35,9 +35,9 @@ Depending on your use case, you might prefer to use a different library, but if Here's a small preview of how you could integrate Strawberry with FastAPI: -```Python hl_lines="3 22 25-26" -{!../../docs_src/graphql/tutorial001.py!} -``` + +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} + You can learn more about Strawberry in the Strawberry documentation. From a1572b52de098cc48c7306d9bdb5d791e554cd6e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:19:49 +0000 Subject: [PATCH 06/83] =?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 d9f5e1b4f..2f299f4e3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/how-to/graphql.md`. PR [#12564](https://github.com/fastapi/fastapi/pull/12564) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes in `docs/en/docs/how-to/extending-openapi.md`. PR [#12562](https://github.com/fastapi/fastapi/pull/12562) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes for `docs/en/docs/how-to/configure-swagger-ui.md`. PR [#12556](https://github.com/fastapi/fastapi/pull/12556) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes for `docs/en/docs/how-to/separate-openapi-schemas.md`. PR [#12555](https://github.com/fastapi/fastapi/pull/12555) by [@tiangolo](https://github.com/tiangolo). From 1fbbf9ca6c71e011d9761cbe9cd21747e6101ae1 Mon Sep 17 00:00:00 2001 From: Ismail Tlemcani Date: Sun, 27 Oct 2024 16:21:34 +0100 Subject: [PATCH 07/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/python-types.md`=20(#12558)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/python-types.md | 57 ++++++++++-------------------------- 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 2992347be..8a0f1f3f4 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -23,9 +23,7 @@ Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annota Prenons un exemple simple : -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py*} Exécuter ce programe affiche : @@ -39,9 +37,7 @@ La fonction : * Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`. * Concatène les résultats avec un espace entre les deux. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py hl[2] *} ### Limitations @@ -84,9 +80,7 @@ C'est tout. Ce sont des annotations de types : -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{*../../docs_src/python_types/tutorial002.py hl[1] *} À ne pas confondre avec la déclaration de valeurs par défaut comme ici : @@ -114,9 +108,7 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle Cette fonction possède déjà des annotations de type : -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{*../../docs_src/python_types/tutorial003.py hl[1] *} Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs : @@ -124,9 +116,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut Maintenant que vous avez connaissance du problème, convertissez `age` en 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 hl[2] *} ## Déclarer des types @@ -145,9 +135,7 @@ Comme par exemple : * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{*../../docs_src/python_types/tutorial005.py hl[1] *} ### Types génériques avec des paramètres de types @@ -163,9 +151,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 hl[1] *} Déclarez la variable, en utilisant la syntaxe des deux-points (`:`). @@ -173,9 +159,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 hl[4] *} /// tip | "Astuce" @@ -201,9 +185,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 hl[1,4] *} Dans cet exemple : @@ -216,9 +198,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 hl[1,4] *} Dans cet exemple : @@ -230,9 +210,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 hl[1,4] *} 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`. @@ -255,15 +233,12 @@ 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 hl[1:3] *} + 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 hl[6] *} Et vous aurez accès, encore une fois, au support complet offert par l'éditeur : @@ -283,9 +258,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 From 4ae5fab050d40025541c26e9122f8ab862aca8ce Mon Sep 17 00:00:00 2001 From: Farhan Ali Raza <62690310+FarhanAliRaza@users.noreply.github.com> Date: Sun, 27 Oct 2024 20:22:48 +0500 Subject: [PATCH 08/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/background-tasks.md`=20(#12559)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/background-tasks.md | 62 ++--------------------- 1 file changed, 4 insertions(+), 58 deletions(-) diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 1cd460b07..92427e36e 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -15,9 +15,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 hl[1,13] *} **FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter. @@ -33,17 +31,13 @@ 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 hl[6:9] *} ## Add the background task 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 hl[14] *} `.add_task()` receives as arguments: @@ -57,57 +51,9 @@ 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: -//// 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 hl[13,15,22,25] *} -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// 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 - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```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. From 4f5349445d234b224ecdb9cb7c562d21919e77b1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:24:00 +0000 Subject: [PATCH 09/83] =?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 2f299f4e3..cd9b6872a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/python-types.md`. PR [#12558](https://github.com/fastapi/fastapi/pull/12558) by [@Ismailtlem](https://github.com/Ismailtlem). * 📝 Update includes in `docs/en/docs/how-to/graphql.md`. PR [#12564](https://github.com/fastapi/fastapi/pull/12564) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes in `docs/en/docs/how-to/extending-openapi.md`. PR [#12562](https://github.com/fastapi/fastapi/pull/12562) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes for `docs/en/docs/how-to/configure-swagger-ui.md`. PR [#12556](https://github.com/fastapi/fastapi/pull/12556) by [@tiangolo](https://github.com/tiangolo). From 13f3dd2111cb1bdcb1a31dfc191a4e3738db64c8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:24:07 +0000 Subject: [PATCH 10/83] =?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 cd9b6872a..e27571ea0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/background-tasks.md`. PR [#12559](https://github.com/fastapi/fastapi/pull/12559) by [@FarhanAliRaza](https://github.com/FarhanAliRaza). * 📝 Update includes in `docs/fr/docs/python-types.md`. PR [#12558](https://github.com/fastapi/fastapi/pull/12558) by [@Ismailtlem](https://github.com/Ismailtlem). * 📝 Update includes in `docs/en/docs/how-to/graphql.md`. PR [#12564](https://github.com/fastapi/fastapi/pull/12564) by [@philipokiokio](https://github.com/philipokiokio). * 📝 Update includes in `docs/en/docs/how-to/extending-openapi.md`. PR [#12562](https://github.com/fastapi/fastapi/pull/12562) by [@philipokiokio](https://github.com/philipokiokio). From 92bc3d7e0c73876f3fb9b01d9ee69a7cf8c4e971 Mon Sep 17 00:00:00 2001 From: ilacftemp <159066669+ilacftemp@users.noreply.github.com> Date: Sun, 27 Oct 2024 12:25:29 -0300 Subject: [PATCH 11/83] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20transla?= =?UTF-8?q?tion=20for=20`docs/pt/docs/tutorial/sql-databases.md`=20(#12530?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/sql-databases.md | 359 +++++++++++++++++++++++++ 1 file changed, 359 insertions(+) create mode 100644 docs/pt/docs/tutorial/sql-databases.md diff --git a/docs/pt/docs/tutorial/sql-databases.md b/docs/pt/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..3d76a532c --- /dev/null +++ b/docs/pt/docs/tutorial/sql-databases.md @@ -0,0 +1,359 @@ +# Bancos de Dados SQL (Relacionais) + +**FastAPI** não exige que você use um banco de dados SQL (relacional). Mas você pode usar **qualquer banco de dados** que quiser. + +Aqui veremos um exemplo usando SQLModel. + +**SQLModel** é construído sobre SQLAlchemy e Pydantic. Ele foi criado pelo mesmo autor do **FastAPI** para ser o par perfeito para aplicações **FastAPI** que precisam usar **bancos de dados SQL**. + +/// tip | Dica + +Você pode usar qualquer outra biblioteca de banco de dados SQL ou NoSQL que quiser (em alguns casos chamadas de "ORMs"), o FastAPI não obriga você a usar nada. 😎 + +/// + +Como o SQLModel é baseado no SQLAlchemy, você pode facilmente usar **qualquer banco de dados suportado** pelo SQLAlchemy (o que também os torna suportados pelo SQLModel), como: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, etc. + +Neste exemplo, usaremos **SQLite**, porque ele usa um único arquivo e o Python tem suporte integrado. Assim, você pode copiar este exemplo e executá-lo como está. + +Mais tarde, para sua aplicação em produção, você pode querer usar um servidor de banco de dados como o **PostgreSQL**. + +/// tip | Dica + +Existe um gerador de projetos oficial com **FastAPI** e **PostgreSQL** incluindo um frontend e mais ferramentas: https://github.com/fastapi/full-stack-fastapi-template + +/// + +Este é um tutorial muito simples e curto, se você quiser aprender sobre bancos de dados em geral, sobre SQL ou recursos mais avançados, acesse a documentação do SQLModel. + +## Instalar o `SQLModel` + +Primeiro, certifique-se de criar seu [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, instalar o `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Criar o App com um Único Modelo + +Vamos criar a primeira versão mais simples do app com um único modelo **SQLModel**. + +Depois, vamos melhorá-lo aumentando a segurança e versatilidade com **múltiplos modelos** abaixo. 🤓 + +### Criar Modelos + +Importe o `SQLModel` e crie um modelo de banco de dados: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +A classe `Hero` é muito semelhante a um modelo Pydantic (na verdade, por baixo dos panos, ela *é um modelo Pydantic*). + +Existem algumas diferenças: + +* `table=True` informa ao SQLModel que este é um *modelo de tabela*, ele deve representar uma **tabela** no banco de dados SQL, não é apenas um *modelo de dados* (como seria qualquer outra classe Pydantic comum). + +* `Field(primary_key=True)` informa ao SQLModel que o `id` é a **chave primária** no banco de dados SQL (você pode aprender mais sobre chaves primárias SQL na documentação do SQLModel). + + Ao ter o tipo como `int | None`, o SQLModel saberá que essa coluna deve ser um `INTEGER` no banco de dados SQL e que ela deve ser `NULLABLE`. + +* `Field(index=True)` informa ao SQLModel que ele deve criar um **índice SQL** para essa coluna, o que permitirá buscas mais rápidas no banco de dados ao ler dados filtrados por essa coluna. + + O SQLModel saberá que algo declarado como `str` será uma coluna SQL do tipo `TEXT` (ou `VARCHAR`, dependendo do banco de dados). + +### Criar um Engine +Um `engine` SQLModel (por baixo dos panos, ele é na verdade um `engine` do SQLAlchemy) é o que **mantém as conexões** com o banco de dados. + +Você teria **um único objeto `engine`** para todo o seu código se conectar ao mesmo banco de dados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Usar `check_same_thread=False` permite que o FastAPI use o mesmo banco de dados SQLite em diferentes threads. Isso é necessário, pois **uma única requisição** pode usar **mais de uma thread** (por exemplo, em dependências). + +Não se preocupe, com a forma como o código está estruturado, garantiremos que usamos **uma única *sessão* SQLModel por requisição** mais tarde, isso é realmente o que o `check_same_thread` está tentando conseguir. + +### Criar as Tabelas + +Em seguida, adicionamos uma função que usa `SQLModel.metadata.create_all(engine)` para **criar as tabelas** para todos os *modelos de tabela*. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Criar uma Dependência de Sessão + +Uma **`Session`** é o que armazena os **objetos na memória** e acompanha as alterações necessárias nos dados, para então **usar o `engine`** para se comunicar com o banco de dados. + +Vamos criar uma **dependência** do FastAPI com `yield` que fornecerá uma nova `Session` para cada requisição. Isso é o que garante que usamos uma única sessão por requisição. 🤓 + +Então, criamos uma dependência `Annotated` chamada `SessionDep` para simplificar o restante do código que usará essa dependência. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Criar Tabelas de Banco de Dados na Inicialização + +Vamos criar as tabelas do banco de dados quando o aplicativo for iniciado. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +Aqui, criamos as tabelas em um evento de inicialização do aplicativo. + +Para produção, você provavelmente usaria um script de migração que é executado antes de iniciar seu app. 🤓 + +/// tip | Dica + +O SQLModel terá utilitários de migração envolvendo o Alembic, mas por enquanto, você pode usar o Alembic diretamente. + +/// + +### Criar um Hero + +Como cada modelo SQLModel também é um modelo Pydantic, você pode usá-lo nas mesmas **anotações de tipo** que usaria para modelos Pydantic. + +Por exemplo, se você declarar um parâmetro do tipo `Hero`, ele será lido do **corpo JSON**. + +Da mesma forma, você pode declará-lo como o **tipo de retorno** da função, e então o formato dos dados aparecerá na interface de documentação automática da API. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +Aqui, usamos a dependência `SessionDep` (uma `Session`) para adicionar o novo `Hero` à instância `Session`, fazer commit das alterações no banco de dados, atualizar os dados no `hero` e então retorná-lo. + +### Ler Heroes + +Podemos **ler** `Hero`s do banco de dados usando um `select()`. Podemos incluir um `limit` e `offset` para paginar os resultados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Ler um Único Hero + +Podemos **ler** um único `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Deletar um Hero + +Também podemos **deletar** um `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Executar o App + +Você pode executar o app: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, vá para a interface `/docs`, você verá que o **FastAPI** está usando esses **modelos** para **documentar** a API, e ele também os usará para **serializar** e **validar** os dados. + +
+ +
+ +## Atualizar o App com Múltiplos Modelos + +Agora vamos **refatorar** este app um pouco para aumentar a **segurança** e **versatilidade**. + +Se você verificar o app anterior, na interface você pode ver que, até agora, ele permite que o cliente decida o `id` do `Hero` a ser criado. 😱 + +Não deveríamos deixar isso acontecer, eles poderiam sobrescrever um `id` que já atribuimos na base de dados. Decidir o `id` deve ser feito pelo **backend** ou pelo **banco de dados**, **não pelo cliente**. + +Além disso, criamos um `secret_name` para o hero, mas até agora estamos retornando ele em todos os lugares, isso não é muito **secreto**... 😅 + +Vamos corrigir essas coisas adicionando alguns **modelos extras**. Aqui é onde o SQLModel vai brilhar. ✨ + +### Criar Múltiplos Modelos + +No **SQLModel**, qualquer classe de modelo que tenha `table=True` é um **modelo de tabela**. + +E qualquer classe de modelo que não tenha `table=True` é um **modelo de dados**, esses são na verdade apenas modelos Pydantic (com alguns recursos extras pequenos). 🤓 + +Com o SQLModel, podemos usar a **herança** para **evitar duplicação** de todos os campos em todos os casos. + +#### `HeroBase` - a classe base + +Vamos começar com um modelo `HeroBase` que tem todos os **campos compartilhados** por todos os modelos: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - o *modelo de tabela* + +Em seguida, vamos criar `Hero`, o verdadeiro *modelo de tabela*, com os **campos extras** que nem sempre estão nos outros modelos: + +* `id` +* `secret_name` + +Como `Hero` herda de `HeroBase`, ele **também** tem os **campos** declarados em `HeroBase`, então todos os campos para `Hero` são: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - o *modelo de dados* público + +Em seguida, criamos um modelo `HeroPublic`, que será **retornado** para os clientes da API. + +Ele tem os mesmos campos que `HeroBase`, então não incluirá `secret_name`. + +Finalmente, a identidade dos nossos heróis está protegida! 🥷 + +Ele também declara novamente `id: int`. Ao fazer isso, estamos fazendo um **contrato** com os clientes da API, para que eles possam sempre esperar que o `id` estará lá e será um `int` (nunca será `None`). + +/// tip | Dica + +Fazer com que o modelo de retorno garanta que um valor esteja sempre disponível e sempre seja um `int` (não `None`) é muito útil para os clientes da API, eles podem escrever código muito mais simples com essa certeza. + +Além disso, **clientes gerados automaticamente** terão interfaces mais simples, para que os desenvolvedores que se comunicam com sua API possam ter uma experiência muito melhor trabalhando com sua API. 😎 + +/// + +Todos os campos em `HeroPublic` são os mesmos que em `HeroBase`, com `id` declarado como `int` (não `None`): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - o *modelo de dados* para criar um hero + +Agora criamos um modelo `HeroCreate`, este é o que **validará** os dados dos clientes. + +Ele tem os mesmos campos que `HeroBase`, e também tem `secret_name`. + +Agora, quando os clientes **criarem um novo hero**, eles enviarão o `secret_name`, ele será armazenado no banco de dados, mas esses nomes secretos não serão retornados na API para os clientes. + +/// tip | Dica + +É assim que você trataria **senhas**. Receba-as, mas não as retorne na API. + +Você também faria um **hash** com os valores das senhas antes de armazená-los, **nunca os armazene em texto simples**. + +/// + +Os campos de `HeroCreate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - o *modelo de dados* para atualizar um hero + +Não tínhamos uma maneira de **atualizar um hero** na versão anterior do app, mas agora com **múltiplos modelos**, podemos fazer isso. 🎉 + +O *modelo de dados* `HeroUpdate` é um pouco especial, ele tem **todos os mesmos campos** que seriam necessários para criar um novo hero, mas todos os campos são **opcionais** (todos têm um valor padrão). Dessa forma, quando você atualizar um hero, poderá enviar apenas os campos que deseja atualizar. + +Como todos os **campos realmente mudam** (o tipo agora inclui `None` e eles agora têm um valor padrão de `None`), precisamos **declarar novamente** todos eles. + +Não precisamos herdar de `HeroBase`, pois estamos redeclarando todos os campos. Vou deixá-lo herdando apenas por consistência, mas isso não é necessário. É mais uma questão de gosto pessoal. 🤷 + +Os campos de `HeroUpdate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Criar com `HeroCreate` e retornar um `HeroPublic` + +Agora que temos **múltiplos modelos**, podemos atualizar as partes do app que os utilizam. + +Recebemos na requisição um *modelo de dados* `HeroCreate`, e a partir dele, criamos um *modelo de tabela* `Hero`. + +Esse novo *modelo de tabela* `Hero` terá os campos enviados pelo cliente, e também terá um `id` gerado pelo banco de dados. + +Em seguida, retornamos o mesmo *modelo de tabela* `Hero` como está na função. Mas como declaramos o `response_model` com o *modelo de dados* `HeroPublic`, o **FastAPI** usará `HeroPublic` para validar e serializar os dados. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Dica + +Agora usamos `response_model=HeroPublic` em vez da **anotação de tipo de retorno** `-> HeroPublic` porque o valor que estamos retornando na verdade *não* é um `HeroPublic`. + +Se tivéssemos declarado `-> HeroPublic`, seu editor e o linter reclamariam (com razão) que você está retornando um `Hero` em vez de um `HeroPublic`. + +Ao declará-lo no `response_model`, estamos dizendo ao **FastAPI** para fazer o seu trabalho, sem interferir nas anotações de tipo e na ajuda do seu editor e de outras ferramentas. + +/// + +### Ler Heroes com `HeroPublic` + +Podemos fazer o mesmo que antes para **ler** `Hero`s, novamente, usamos `response_model=list[HeroPublic]` para garantir que os dados sejam validados e serializados corretamente. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Ler Um Hero com `HeroPublic` + +Podemos **ler** um único herói: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Atualizar um Hero com `HeroUpdate` + +Podemos **atualizar um hero**. Para isso, usamos uma operação HTTP `PATCH`. + +E no código, obtemos um `dict` com todos os dados enviados pelo cliente, **apenas os dados enviados pelo cliente**, excluindo quaisquer valores que estariam lá apenas por serem os valores padrão. Para fazer isso, usamos `exclude_unset=True`. Este é o truque principal. 🪄 + +Em seguida, usamos `hero_db.sqlmodel_update(hero_data)` para atualizar o `hero_db` com os dados de `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Deletar um Hero Novamente + +**Deletar** um hero permanece praticamente o mesmo. + +Não vamos satisfazer o desejo de refatorar tudo neste aqui. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Executar o App Novamente + +Você pode executar o app novamente: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +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. + +
+ +
+ +## Recapitulando + +Você pode usar **SQLModel** para interagir com um banco de dados SQL e simplificar o código com *modelos de dados* e *modelos de tabela*. + +Você pode aprender muito mais na documentação do **SQLModel**, há um mini tutorial sobre como usar SQLModel com **FastAPI** mais longo. 🚀 From b87eb8a0e1698e5fdb59d13de8aa091d7a1b9f69 Mon Sep 17 00:00:00 2001 From: Nimitha J <58389915+Nimitha-jagadeesha@users.noreply.github.com> Date: Sun, 27 Oct 2024 20:55:54 +0530 Subject: [PATCH 12/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/de/docs/advanced/security/http-basic-auth.md`=20(#12561)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 91 +------------------ 1 file changed, 3 insertions(+), 88 deletions(-) diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md index 4e607e6a1..36498c01d 100644 --- a/docs/de/docs/advanced/security/http-basic-auth.md +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -20,36 +20,7 @@ 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`. -//// 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+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// - +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} 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: @@ -68,35 +39,7 @@ 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. -//// 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+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} Dies wäre das gleiche wie: @@ -160,32 +103,4 @@ 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: -//// 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+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} From 909204ec5452e9f2f9fe542802386c9b8802efc2 Mon Sep 17 00:00:00 2001 From: Alexandros Mioglou Date: Sun, 27 Oct 2024 17:28:18 +0200 Subject: [PATCH 13/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/pt/docs/advanced/behind-a-proxy.md`=20(#12563)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/behind-a-proxy.md | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 3c65b5a0a..12fd83f3d 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -18,9 +18,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 hl[6] *} 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`. @@ -98,9 +96,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 hl[8] *} Então, se você iniciar o Uvicorn com: @@ -127,9 +123,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 hl[3] *} 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. @@ -309,9 +303,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 hl[4:7] *} Gerará um OpenAPI schema como: @@ -358,9 +350,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 hl[9] *} e então ele não será incluído no OpenAPI schema. From e00efb55691fd3d2b5c8f7759ff72329291e161f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:29:12 +0000 Subject: [PATCH 14/83] =?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 e27571ea0..0e8328b86 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/sql-databases.md`. PR [#12530](https://github.com/fastapi/fastapi/pull/12530) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Add Korean translation for `docs/ko/docs/benchmarks.md`. PR [#12540](https://github.com/fastapi/fastapi/pull/12540) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/separate-openapi-schemas.md`. PR [#12518](https://github.com/fastapi/fastapi/pull/12518) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12521](https://github.com/fastapi/fastapi/pull/12521) by [@codingjenny](https://github.com/codingjenny). From 91eb00854bf71c62eaa320971cd97a1305831dfb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:30:02 +0000 Subject: [PATCH 15/83] =?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 0e8328b86..d4486a2db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#12561](https://github.com/fastapi/fastapi/pull/12561) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes in `docs/en/docs/tutorial/background-tasks.md`. PR [#12559](https://github.com/fastapi/fastapi/pull/12559) by [@FarhanAliRaza](https://github.com/FarhanAliRaza). * 📝 Update includes in `docs/fr/docs/python-types.md`. PR [#12558](https://github.com/fastapi/fastapi/pull/12558) by [@Ismailtlem](https://github.com/Ismailtlem). * 📝 Update includes in `docs/en/docs/how-to/graphql.md`. PR [#12564](https://github.com/fastapi/fastapi/pull/12564) by [@philipokiokio](https://github.com/philipokiokio). From 48f88edf0dc5ffa22829966e0640a57cd192aac2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:33:12 +0000 Subject: [PATCH 16/83] =?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 d4486a2db..cb005d696 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#12563](https://github.com/fastapi/fastapi/pull/12563) by [@asmioglou](https://github.com/asmioglou). * 📝 Update includes in `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#12561](https://github.com/fastapi/fastapi/pull/12561) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes in `docs/en/docs/tutorial/background-tasks.md`. PR [#12559](https://github.com/fastapi/fastapi/pull/12559) by [@FarhanAliRaza](https://github.com/FarhanAliRaza). * 📝 Update includes in `docs/fr/docs/python-types.md`. PR [#12558](https://github.com/fastapi/fastapi/pull/12558) by [@Ismailtlem](https://github.com/Ismailtlem). From 27e7fcefe858024a3b47c07fdfae916a228b6615 Mon Sep 17 00:00:00 2001 From: Julio Anthony Leonard Date: Sun, 27 Oct 2024 16:34:47 +0100 Subject: [PATCH 17/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/de/docs/advanced/async-tests.md`=20(#12567)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/async-tests.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 93ff84b8a..6c1981e25 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -60,9 +60,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 hl[7] *} /// tip | "Tipp" @@ -72,9 +70,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 hl[9:12] *} Das ist das Äquivalent zu: From 4b9e76bde26bec5a7b783b4d0043b2fc0d6ebfe0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:39:25 +0000 Subject: [PATCH 18/83] =?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 cb005d696..cd35be4d5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 📝 Update includes in `docs/de/docs/advanced/async-tests.md`. PR [#12567](https://github.com/fastapi/fastapi/pull/12567) by [@imjuanleonard](https://github.com/imjuanleonard). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/sql-databases.md`. PR [#12530](https://github.com/fastapi/fastapi/pull/12530) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Add Korean translation for `docs/ko/docs/benchmarks.md`. PR [#12540](https://github.com/fastapi/fastapi/pull/12540) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/separate-openapi-schemas.md`. PR [#12518](https://github.com/fastapi/fastapi/pull/12518) by [@ilacftemp](https://github.com/ilacftemp). From dfdecfd9c93e8cfb07e46709e5a6966ff9c36bdc Mon Sep 17 00:00:00 2001 From: Krishna Madhavan Date: Sun, 27 Oct 2024 21:13:29 +0530 Subject: [PATCH 19/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/async-tests.md`=20(#12568)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/async-tests.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index 232cd6e57..8d6929222 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ 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 @@ -60,9 +56,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 hl[7] *} /// tip @@ -72,9 +66,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 hl[9:12] *} This is the equivalent to: From b24b4fd6a810dad86c470e072e0603ebc0f223f4 Mon Sep 17 00:00:00 2001 From: Nomad Monad <38782977+lucaromagnoli@users.noreply.github.com> Date: Sun, 27 Oct 2024 15:45:40 +0000 Subject: [PATCH 20/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/static-files.md`=20(#12575)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/static-files.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 2e93bd60b..46affd4f2 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ You can serve static files automatically from a directory using `StaticFiles`. * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | "Technical Details" From ed45eca1a886791ccfa0f32c7a7805ad4a78c826 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:50:02 +0000 Subject: [PATCH 21/83] =?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 cd35be4d5..793f34b99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/async-tests.md`. PR [#12568](https://github.com/fastapi/fastapi/pull/12568) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#12563](https://github.com/fastapi/fastapi/pull/12563) by [@asmioglou](https://github.com/asmioglou). * 📝 Update includes in `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#12561](https://github.com/fastapi/fastapi/pull/12561) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes in `docs/en/docs/tutorial/background-tasks.md`. PR [#12559](https://github.com/fastapi/fastapi/pull/12559) by [@FarhanAliRaza](https://github.com/FarhanAliRaza). From 55aa76faad5834b017282ed0e44b60f0ee61e184 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 15:51:51 +0000 Subject: [PATCH 22/83] =?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 793f34b99..95e5b5f18 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/static-files.md`. PR [#12575](https://github.com/fastapi/fastapi/pull/12575) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/async-tests.md`. PR [#12568](https://github.com/fastapi/fastapi/pull/12568) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#12563](https://github.com/fastapi/fastapi/pull/12563) by [@asmioglou](https://github.com/asmioglou). * 📝 Update includes in `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#12561](https://github.com/fastapi/fastapi/pull/12561) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). From 0f8d03ef854a3e57bf7beba8f7a2bacd1926919d Mon Sep 17 00:00:00 2001 From: Krishna Madhavan Date: Sun, 27 Oct 2024 21:37:07 +0530 Subject: [PATCH 23/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/additional-responses.md`=20(#12576)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/additional-responses.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index c038096f9..03d48c2a7 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -26,9 +26,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 hl[18,22] *} /// note @@ -177,9 +175,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 hl[19:24,28] *} /// note @@ -207,9 +203,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 hl[20:31] *} It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -243,9 +237,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 hl[13:17,26] *} ## More information about OpenAPI responses From dc22bdf5a4ba019543eaba0b00cf3a037f6bdb5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 16:08:49 +0000 Subject: [PATCH 24/83] =?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 95e5b5f18..c4c7f98af 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/additional-responses.md`. PR [#12576](https://github.com/fastapi/fastapi/pull/12576) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/tutorial/static-files.md`. PR [#12575](https://github.com/fastapi/fastapi/pull/12575) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/async-tests.md`. PR [#12568](https://github.com/fastapi/fastapi/pull/12568) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#12563](https://github.com/fastapi/fastapi/pull/12563) by [@asmioglou](https://github.com/asmioglou). From 9106cae8a8cc0c46069cf2885f1bce9fdc200ee2 Mon Sep 17 00:00:00 2001 From: Krishna Madhavan Date: Sun, 27 Oct 2024 21:40:15 +0530 Subject: [PATCH 25/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/advanced-dependencies.md`=20(#12578)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../en/docs/advanced/advanced-dependencies.md | 120 +----------------- 1 file changed, 4 insertions(+), 116 deletions(-) diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index b15a4fe3d..f933fd264 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: -//// tab | Python 3.9+ - -```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!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} 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. @@ -54,35 +26,7 @@ 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: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -90,35 +34,7 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -134,35 +50,7 @@ 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`: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```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!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip From dc7cf0f14f1059082310995b2369e5e2a4d8cf1b Mon Sep 17 00:00:00 2001 From: Krishna Madhavan Date: Sun, 27 Oct 2024 21:42:23 +0530 Subject: [PATCH 26/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/additional-status-codes.md`=20(#12577)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/additional-status-codes.md | 52 +------------------ 1 file changed, 1 insertion(+), 51 deletions(-) diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 6105a301c..e39249467 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -14,57 +14,7 @@ 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: -//// tab | Python 3.10+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 26" -{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -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_an_py310.py hl[4,25] *} /// warning From fe60afff0e043d78c3dc686c2d91efdceaf590cb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 16:13:50 +0000 Subject: [PATCH 27/83] =?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 c4c7f98af..492003f3d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/advanced-dependencies.md`. PR [#12578](https://github.com/fastapi/fastapi/pull/12578) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/additional-responses.md`. PR [#12576](https://github.com/fastapi/fastapi/pull/12576) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/tutorial/static-files.md`. PR [#12575](https://github.com/fastapi/fastapi/pull/12575) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/async-tests.md`. PR [#12568](https://github.com/fastapi/fastapi/pull/12568) by [@krishnamadhavan](https://github.com/krishnamadhavan). From f5a10c1c7d666013520a4300fae5bb3af4e4769f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 16:17:51 +0000 Subject: [PATCH 28/83] =?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 492003f3d..27d870468 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/additional-status-codes.md`. PR [#12577](https://github.com/fastapi/fastapi/pull/12577) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/advanced-dependencies.md`. PR [#12578](https://github.com/fastapi/fastapi/pull/12578) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/additional-responses.md`. PR [#12576](https://github.com/fastapi/fastapi/pull/12576) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/tutorial/static-files.md`. PR [#12575](https://github.com/fastapi/fastapi/pull/12575) by [@lucaromagnoli](https://github.com/lucaromagnoli). From 5d99a42688ab50053db42e89c021cf604cf7f83c Mon Sep 17 00:00:00 2001 From: Graziano Montanaro <40232320+montanarograziano@users.noreply.github.com> Date: Sun, 27 Oct 2024 17:45:50 +0100 Subject: [PATCH 29/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/middleware.md`=20(#12582)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/middleware.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 07deac716..3faf3fbf9 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -57,17 +57,13 @@ 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 hl[2,6] *} ## `TrustedHostMiddleware` 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 hl[2,6:8] *} The following arguments are supported: @@ -81,9 +77,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 hl[2,6] *} The following arguments are supported: From 5b1963db4911b27d335c5c2e2944ad113173e44f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 16:46:14 +0000 Subject: [PATCH 30/83] =?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 27d870468..e2b3eff3d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/middleware.md`. PR [#12582](https://github.com/fastapi/fastapi/pull/12582) by [@montanarograziano](https://github.com/montanarograziano). * 📝 Update includes in `docs/en/docs/advanced/additional-status-codes.md`. PR [#12577](https://github.com/fastapi/fastapi/pull/12577) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/advanced-dependencies.md`. PR [#12578](https://github.com/fastapi/fastapi/pull/12578) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/additional-responses.md`. PR [#12576](https://github.com/fastapi/fastapi/pull/12576) by [@krishnamadhavan](https://github.com/krishnamadhavan). From f0ad433e01cd074eb2e9575df59ea0eac15dedfb Mon Sep 17 00:00:00 2001 From: Julio Anthony Leonard Date: Sun, 27 Oct 2024 17:49:49 +0100 Subject: [PATCH 31/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/behind-a-proxy.md`=20(#12583)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/behind-a-proxy.md | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 67718a27b..87a62e88b 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -18,9 +18,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 hl[6] *} 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`. @@ -98,9 +96,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 hl[8] *} Then, if you start Uvicorn with: @@ -127,9 +123,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 hl[3] *} Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. @@ -309,9 +303,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 hl[4:7] *} Will generate an OpenAPI schema like: @@ -358,9 +350,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 hl[9] *} and then it won't include it in the OpenAPI schema. From 3783341eb8b900899ca3ec09f100c8fe4e719f8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Koz=C5=82owski?= <82809231+sebkozlo@users.noreply.github.com> Date: Sun, 27 Oct 2024 17:51:30 +0100 Subject: [PATCH 32/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20syntax?= =?UTF-8?q?=20for=20`docs/pl/docs/tutorial/first-steps.md`=20(#12584)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pl/docs/tutorial/first-steps.md | 32 +++++++--------------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 99c425f12..9466ca84d 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -2,9 +2,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`. @@ -133,9 +131,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 hl[1] *} `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. @@ -149,9 +145,7 @@ Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Date: Sun, 27 Oct 2024 16:52:28 +0000 Subject: [PATCH 33/83] =?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 e2b3eff3d..7052d97b0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes syntax for `docs/pl/docs/tutorial/first-steps.md`. PR [#12584](https://github.com/fastapi/fastapi/pull/12584) by [@sebkozlo](https://github.com/sebkozlo). * 📝 Update includes in `docs/en/docs/advanced/middleware.md`. PR [#12582](https://github.com/fastapi/fastapi/pull/12582) by [@montanarograziano](https://github.com/montanarograziano). * 📝 Update includes in `docs/en/docs/advanced/additional-status-codes.md`. PR [#12577](https://github.com/fastapi/fastapi/pull/12577) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 Update includes in `docs/en/docs/advanced/advanced-dependencies.md`. PR [#12578](https://github.com/fastapi/fastapi/pull/12578) by [@krishnamadhavan](https://github.com/krishnamadhavan). From 75af54babd74ae99d3ecfdc012ef005a940e3727 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 16:52:29 +0000 Subject: [PATCH 34/83] =?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 7052d97b0..72febff86 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#12583](https://github.com/fastapi/fastapi/pull/12583) by [@imjuanleonard](https://github.com/imjuanleonard). * 📝 Update includes syntax for `docs/pl/docs/tutorial/first-steps.md`. PR [#12584](https://github.com/fastapi/fastapi/pull/12584) by [@sebkozlo](https://github.com/sebkozlo). * 📝 Update includes in `docs/en/docs/advanced/middleware.md`. PR [#12582](https://github.com/fastapi/fastapi/pull/12582) by [@montanarograziano](https://github.com/montanarograziano). * 📝 Update includes in `docs/en/docs/advanced/additional-status-codes.md`. PR [#12577](https://github.com/fastapi/fastapi/pull/12577) by [@krishnamadhavan](https://github.com/krishnamadhavan). From 5a0e13794b5f5c1dd3180d9cdd42341fed4bb1c3 Mon Sep 17 00:00:00 2001 From: Nomad Monad <38782977+lucaromagnoli@users.noreply.github.com> Date: Sun, 27 Oct 2024 16:58:19 +0000 Subject: [PATCH 35/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/body.md`=20(#12586)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body.md | 92 ++--------------------------------- 1 file changed, 5 insertions(+), 87 deletions(-) diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 14d621418..9c97f64cb 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -22,21 +22,7 @@ As it is discouraged, the interactive docs with Swagger UI won't show the docume First, you need to import `BaseModel` from `pydantic`: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## Create your data model @@ -44,21 +30,8 @@ Then you declare your data model as a class that inherits from `BaseModel`. 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 hl[5:9] *} -//// 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. @@ -86,21 +59,7 @@ 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: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ...and declare its type as the model you created, `Item`. @@ -167,21 +126,7 @@ It improves editor support for Pydantic models, with: Inside of the function, you can access all the attributes of the model object directly: -//// tab | Python 3.10+ - -```Python hl_lines="19" {!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// ## Request body + path parameters @@ -189,21 +134,8 @@ 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**. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// ## Request body + path + query parameters @@ -211,21 +143,7 @@ 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. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} The function parameters will be recognized as follows: From 503ece76d6eabc2357b86a98455ebb8fbc83ff9d Mon Sep 17 00:00:00 2001 From: Alexander Bejarano Date: Sun, 27 Oct 2024 17:59:43 +0100 Subject: [PATCH 36/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/de/docs/tutorial/response-status-code.md`=20(#12585)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/response-status-code.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index 872007a12..5f017355b 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo * `@app.delete()` * usw. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | "Hinweis" @@ -76,9 +74,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 hl[6] *} `201` ist der Statuscode für „Created“ („Erzeugt“). @@ -86,9 +82,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 hl[1,6] *} 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: From 47b4e1a517534d442a9e2983fc4d777a2d59d306 Mon Sep 17 00:00:00 2001 From: Nomad Monad <38782977+lucaromagnoli@users.noreply.github.com> Date: Sun, 27 Oct 2024 17:01:18 +0000 Subject: [PATCH 37/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/tutorial/body-fields.md`=20(#12588)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body-fields.md | 103 +-------------------------- 1 file changed, 2 insertions(+), 101 deletions(-) diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 30a5c623f..7f7e34fcc 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -6,57 +6,8 @@ The same way you can declare additional validation and metadata in *path operati First, you have to import it: -//// tab | Python 3.10+ +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```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 @@ -68,57 +19,7 @@ Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as 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!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```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!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc. From cd37dfe533c5409d6ec5b24476ec6b581421022f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:01:22 +0000 Subject: [PATCH 38/83] =?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 72febff86..9bee45856 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/body.md`. PR [#12586](https://github.com/fastapi/fastapi/pull/12586) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#12583](https://github.com/fastapi/fastapi/pull/12583) by [@imjuanleonard](https://github.com/imjuanleonard). * 📝 Update includes syntax for `docs/pl/docs/tutorial/first-steps.md`. PR [#12584](https://github.com/fastapi/fastapi/pull/12584) by [@sebkozlo](https://github.com/sebkozlo). * 📝 Update includes in `docs/en/docs/advanced/middleware.md`. PR [#12582](https://github.com/fastapi/fastapi/pull/12582) by [@montanarograziano](https://github.com/montanarograziano). From ba77d114f61719abf1610e800386c2818071577f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:02:19 +0000 Subject: [PATCH 39/83] =?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 9bee45856..5482f88dc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/de/docs/tutorial/response-status-code.md`. PR [#12585](https://github.com/fastapi/fastapi/pull/12585) by [@abejaranoh](https://github.com/abejaranoh). * 📝 Update includes in `docs/en/docs/tutorial/body.md`. PR [#12586](https://github.com/fastapi/fastapi/pull/12586) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#12583](https://github.com/fastapi/fastapi/pull/12583) by [@imjuanleonard](https://github.com/imjuanleonard). * 📝 Update includes syntax for `docs/pl/docs/tutorial/first-steps.md`. PR [#12584](https://github.com/fastapi/fastapi/pull/12584) by [@sebkozlo](https://github.com/sebkozlo). From 9f44a5dd369e5d9883f2071ab571dd4d4cfb0fc2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:02:42 +0000 Subject: [PATCH 40/83] =?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 5482f88dc..56f12f331 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/tutorial/body-fields.md`. PR [#12588](https://github.com/fastapi/fastapi/pull/12588) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/de/docs/tutorial/response-status-code.md`. PR [#12585](https://github.com/fastapi/fastapi/pull/12585) by [@abejaranoh](https://github.com/abejaranoh). * 📝 Update includes in `docs/en/docs/tutorial/body.md`. PR [#12586](https://github.com/fastapi/fastapi/pull/12586) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#12583](https://github.com/fastapi/fastapi/pull/12583) by [@imjuanleonard](https://github.com/imjuanleonard). From 5e8f1f96ebbaf0a7b9a06ef403d28c327caa746b Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sun, 27 Oct 2024 18:06:01 +0100 Subject: [PATCH 41/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/tutorial/query-params.md`=20(#12589)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/query-params.md | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index c847a8f5b..798f84fa3 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -2,9 +2,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 hl[9] *} 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 `&`. @@ -63,9 +61,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 hl[9] *} Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. @@ -87,9 +83,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 hl[9] *} Avec ce code, en allant sur : @@ -131,9 +125,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 hl[8,10] *} ## Paramètres de requête requis @@ -143,9 +135,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 hl[6:7] *} Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`. @@ -189,9 +179,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 hl[10] *} Ici, on a donc 3 paramètres de requête : From af269cd1317ea52522b23c80501b47917d3af0ac Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:09:22 +0000 Subject: [PATCH 42/83] =?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 56f12f331..45d334c1e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/query-params.md`. PR [#12589](https://github.com/fastapi/fastapi/pull/12589) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/tutorial/body-fields.md`. PR [#12588](https://github.com/fastapi/fastapi/pull/12588) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/de/docs/tutorial/response-status-code.md`. PR [#12585](https://github.com/fastapi/fastapi/pull/12585) by [@abejaranoh](https://github.com/abejaranoh). * 📝 Update includes in `docs/en/docs/tutorial/body.md`. PR [#12586](https://github.com/fastapi/fastapi/pull/12586) by [@lucaromagnoli](https://github.com/lucaromagnoli). From 453f559934362cd8372bb5fda0fe550572a2611e Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sun, 27 Oct 2024 18:14:38 +0100 Subject: [PATCH 43/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/tutorial/query-params-str-validations.md`=20(#1259?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/query-params-str-validations.md | 56 +++++-------------- 1 file changed, 14 insertions(+), 42 deletions(-) diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index b71d1548a..a3cf76302 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,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 hl[9] *} 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. @@ -26,17 +24,13 @@ 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 hl[3] *} ## Utiliser `Query` comme valeur par défaut 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 hl[9] *} 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. @@ -86,17 +80,13 @@ 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 hl[9] *} ## Ajouter des validations par expressions régulières 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 hl[10] *} Cette expression régulière vérifie que la valeur passée comme paramètre : @@ -114,9 +104,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 hl[7] *} /// note | "Rappel" @@ -146,9 +134,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 hl[7] *} /// info @@ -164,9 +150,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 hl[9] *} Ce qui fait qu'avec une URL comme : @@ -201,9 +185,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 hl[9] *} Si vous allez à : @@ -228,9 +210,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 hl[7] *} /// note @@ -256,15 +236,11 @@ 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 hl[10] *} Et une `description` : -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Alias de paramètres @@ -284,9 +260,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 hl[9] *} ## Déprécier des paramètres @@ -296,9 +270,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 hl[18] *} La documentation le présentera comme il suit : From 2a4cf1736da0c6f004a0ea3d20b224cc2d4cf5d3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:16:01 +0000 Subject: [PATCH 44/83] =?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 45d334c1e..47093e6ca 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/query-params-str-validations.md`. PR [#12591](https://github.com/fastapi/fastapi/pull/12591) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/query-params.md`. PR [#12589](https://github.com/fastapi/fastapi/pull/12589) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/tutorial/body-fields.md`. PR [#12588](https://github.com/fastapi/fastapi/pull/12588) by [@lucaromagnoli](https://github.com/lucaromagnoli). * 📝 Update includes in `docs/de/docs/tutorial/response-status-code.md`. PR [#12585](https://github.com/fastapi/fastapi/pull/12585) by [@abejaranoh](https://github.com/abejaranoh). From 60aba0261cb0d7a418acfc46527a152805e72007 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sun, 27 Oct 2024 18:31:14 +0100 Subject: [PATCH 45/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/tutorial/debugging.md`=20(#12595)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/debugging.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index 914277699..ab00fbdeb 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -6,9 +6,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 hl[1,15] *} ### À propos de `__name__ == "__main__"` From 9b1e5f29e61975bfec0c35d1c2ec46620fbbc714 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:31:38 +0000 Subject: [PATCH 46/83] =?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 47093e6ca..0ca14b122 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/debugging.md`. PR [#12595](https://github.com/fastapi/fastapi/pull/12595) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/query-params-str-validations.md`. PR [#12591](https://github.com/fastapi/fastapi/pull/12591) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/query-params.md`. PR [#12589](https://github.com/fastapi/fastapi/pull/12589) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/tutorial/body-fields.md`. PR [#12588](https://github.com/fastapi/fastapi/pull/12588) by [@lucaromagnoli](https://github.com/lucaromagnoli). From 4e6b1acccd136c3d19562b57ff844afbac31efe2 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sun, 27 Oct 2024 18:34:41 +0100 Subject: [PATCH 47/83] =?UTF-8?q?=F0=9F=93=9D=20=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/tutorial/body.md`=20(#12596)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/body.md | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 96fff2ca6..c4d493a45 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -22,9 +22,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 hl[4] *} ## Créez votre modèle de données @@ -32,9 +30,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 hl[7:11] *} 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. @@ -62,9 +58,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 hl[18] *} ...et déclarez que son type est le modèle que vous avez créé : `Item`. @@ -131,9 +125,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 hl[21] *} ## Corps de la requête + paramètres de chemin @@ -141,9 +133,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 hl[17:18] *} ## Corps de la requête + paramètres de chemin et de requête @@ -151,9 +141,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 hl[18] *} Les paramètres de la fonction seront reconnus comme tel : From aee7674ed24037c4a7fbc17e2390653ba2055348 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 17:35:05 +0000 Subject: [PATCH 48/83] =?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 0ca14b122..bedd3e5f2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/body.md`. PR [#12596](https://github.com/fastapi/fastapi/pull/12596) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/debugging.md`. PR [#12595](https://github.com/fastapi/fastapi/pull/12595) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/query-params-str-validations.md`. PR [#12591](https://github.com/fastapi/fastapi/pull/12591) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/query-params.md`. PR [#12589](https://github.com/fastapi/fastapi/pull/12589) by [@kantandane](https://github.com/kantandane). From b31cbbf5f5f7680f27c50339ff9fddafadcc3d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 27 Oct 2024 22:46:26 +0100 Subject: [PATCH 49/83] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20logic=20to?= =?UTF-8?q?=20import=20and=20check=20`python-multipart`=20for=20compatibil?= =?UTF-8?q?ity=20with=20newer=20version=20(#12627)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 30 +++++--- tests/test_multipart_installation.py | 107 +++++++++++++++++++-------- 2 files changed, 94 insertions(+), 43 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 87653c80d..e2866b488 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -90,21 +90,29 @@ 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__ + from python_multipart import __version__ - assert __version__ + # Import an attribute that can be mocked/deleted in testing + assert __version__ > "0.0.12" + except (ImportError, AssertionError): try: - # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header + # __version__ is available in both multiparts, and can be mocked + from multipart import __version__ # type: ignore[no-redef,import-untyped] - assert parse_options_header # type: ignore[truthy-function] + assert __version__ + try: + # parse_options_header is only available in the right multipart + from multipart.multipart import ( # type: ignore[import-untyped] + parse_options_header, + ) + + assert parse_options_header + except ImportError: + logger.error(multipart_incorrect_install_error) + raise RuntimeError(multipart_incorrect_install_error) from None except ImportError: - logger.error(multipart_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 + logger.error(multipart_not_installed_error) + raise RuntimeError(multipart_not_installed_error) from None def get_param_sub_dependant( diff --git a/tests/test_multipart_installation.py b/tests/test_multipart_installation.py index 788d9ef5a..9c3e47c49 100644 --- a/tests/test_multipart_installation.py +++ b/tests/test_multipart_installation.py @@ -1,3 +1,5 @@ +import warnings + import pytest from fastapi import FastAPI, File, Form, UploadFile from fastapi.dependencies.utils import ( @@ -7,7 +9,10 @@ from fastapi.dependencies.utils import ( def test_incorrect_multipart_installed_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -17,7 +22,10 @@ def test_incorrect_multipart_installed_form(monkeypatch): def test_incorrect_multipart_installed_file_upload(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -27,7 +35,10 @@ def test_incorrect_multipart_installed_file_upload(monkeypatch): def test_incorrect_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -37,7 +48,10 @@ def test_incorrect_multipart_installed_file_bytes(monkeypatch): def test_incorrect_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -47,7 +61,10 @@ def test_incorrect_multipart_installed_multi_form(monkeypatch): def test_incorrect_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -57,50 +74,76 @@ def test_incorrect_multipart_installed_form_file(monkeypatch): def test_no_multipart_installed(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: UploadFile = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: UploadFile = File()): + return f # pragma: nocover def test_no_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: bytes = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: bytes = File()): + return f # pragma: nocover def test_no_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form(), password: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form(), password: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() + + @app.post("/") + async def root(username: str = Form(), f: UploadFile = File()): + return username # pragma: nocover + + +def test_old_multipart_installed(monkeypatch): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") app = FastAPI() @app.post("/") - async def root(username: str = Form(), f: UploadFile = File()): + async def root(username: str = Form()): return username # pragma: nocover From b270ff1e5eb00bb497078dc3da6ec5f8326ee726 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 21:46:51 +0000 Subject: [PATCH 50/83] =?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 bedd3e5f2..4445419e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Update logic to import and check `python-multipart` for compatibility with newer version. PR [#12627](https://github.com/fastapi/fastapi/pull/12627) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Update includes in `docs/fr/docs/tutorial/body.md`. PR [#12596](https://github.com/fastapi/fastapi/pull/12596) by [@kantandane](https://github.com/kantandane). From 31887b1cc6fb45373b615448627c63410bd37333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 27 Oct 2024 21:51:55 +0000 Subject: [PATCH 51/83] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.115.?= =?UTF-8?q?4?= 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 4445419e5..ea6896f22 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.4 + ### Refactors * ♻️ Update logic to import and check `python-multipart` for compatibility with newer version. PR [#12627](https://github.com/fastapi/fastapi/pull/12627) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 64d5dd39b..51e3ca510 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.3" +__version__ = "0.115.4" from starlette import status as status From 2c27cae742afdf811c25e4e79c4e83406bbd6723 Mon Sep 17 00:00:00 2001 From: namjimin_43 Date: Mon, 28 Oct 2024 07:01:39 +0900 Subject: [PATCH 52/83] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20Translation?= =?UTF-8?q?=20for=20`docs/ko/docs/advanced/response-change-status-code.md`?= =?UTF-8?q?=20(#12547)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../advanced/response-change-status-code.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/ko/docs/advanced/response-change-status-code.md diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..f3cdd2ba5 --- /dev/null +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# 응답 - 상태 코드 변경 + +기본 [응답 상태 코드 설정](../tutorial/response-status-code.md){.internal-link target=_blank}이 가능하다는 걸 이미 알고 계실 겁니다. + +하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다. + +## 사용 예 + +예를 들어 기본적으로 HTTP 상태 코드 "OK" `200`을 반환하고 싶다고 가정해 봅시다. + +하지만 데이터가 존재하지 않으면 이를 새로 생성하고, HTTP 상태 코드 "CREATED" `201`을 반환하고자 할 때가 있을 수 있습니다. + +이때도 여전히 `response_model`을 사용하여 반환하는 데이터를 필터링하고 변환하고 싶을 수 있습니다. + +이런 경우에는 `Response` 파라미터를 사용할 수 있습니다. + +## `Response` 파라미터 사용하기 + +*경로 작동 함수*에 `Response` 타입의 파라미터를 선언할 수 있습니다. (쿠키와 헤더에 대해 선언하는 것과 유사하게) + +그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. + +```Python hl_lines="1 9 12" +{!../../docs_src/response_change_status_code/tutorial001.py!} +``` + +그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언했다면 반환된 객체는 여전히 필터링되고 변환됩니다. + +**FastAPI**는 이 *임시* 응답 객체에서 상태 코드(쿠키와 헤더 포함)를 추출하여, `response_model`로 필터링된 반환 값을 최종 응답에 넣습니다. + +또한, 의존성에서도 `Response` 파라미터를 선언하고 그 안에서 상태 코드를 설정할 수 있습니다. 단, 마지막으로 설정된 상태 코드가 우선 적용된다는 점을 유의하세요. From d92fc89eb8faac9992de534843f57119034ce326 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 22:02:27 +0000 Subject: [PATCH 53/83] =?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 ea6896f22..160116c0d 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/advanced/response-change-status-code.md`. PR [#12547](https://github.com/fastapi/fastapi/pull/12547) by [@9zimin9](https://github.com/9zimin9). + ## 0.115.4 ### Refactors From 78f295609fb27db455e60c5da019bdd73150f5f2 Mon Sep 17 00:00:00 2001 From: Philip Okiokio <55271518+philipokiokio@users.noreply.github.com> Date: Sun, 27 Oct 2024 23:12:32 +0100 Subject: [PATCH 54/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/how-to/custom-request-and-route.md`=20(#12560)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/custom-request-and-route.md | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) 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 a62ebf1d5..f80887c0d 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -42,9 +42,8 @@ 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 hl[8:15] *} + ### Create a custom `GzipRoute` class @@ -56,9 +55,9 @@ 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 hl[18:26] *} + /// note | "Technical Details" @@ -96,26 +95,25 @@ 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 hl[13,15] *} + 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 hl[16:18] *} + + ## Custom `APIRoute` class in a router 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 hl[26] *} + 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 hl[13:20] *} From 5db8b491db1cec45640ec0bd1df9a534bfc525a3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 22:12:53 +0000 Subject: [PATCH 55/83] =?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 160116c0d..2e5ff95dc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio). + ### Translations * 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-change-status-code.md`. PR [#12547](https://github.com/fastapi/fastapi/pull/12547) by [@9zimin9](https://github.com/9zimin9). From eea2d8e67cab83e7136bc4a8328f0f791181215f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 27 Oct 2024 22:39:38 +0000 Subject: [PATCH 56/83] =?UTF-8?q?=F0=9F=8E=A8=20Adjust=20spacing=20(#12635?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/custom-request-and-route.md | 10 ---------- docs/en/docs/how-to/extending-openapi.md | 10 ---------- docs/en/docs/how-to/graphql.md | 2 -- 3 files changed, 22 deletions(-) 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 f80887c0d..25ec0a335 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -44,7 +44,6 @@ That way, the same route class can handle gzip compressed or uncompressed reques {* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} - ### Create a custom `GzipRoute` class Next, we create a custom subclass of `fastapi.routing.APIRoute` that will make use of the `GzipRequest`. @@ -55,10 +54,8 @@ 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. - {* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} - /// note | "Technical Details" A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. @@ -95,25 +92,18 @@ 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: - {* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} - 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: - {* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} - - ## Custom `APIRoute` class in a router You can also set the `route_class` parameter of an `APIRouter`: {* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} - 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: - {* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index 8c7790725..26c742c20 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -45,23 +45,18 @@ First, write all your **FastAPI** application as normally: {* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} - ### Generate the OpenAPI schema Then, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function: - - {* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *} - ### Modify the OpenAPI schema Now you can add the ReDoc extension, adding a custom `x-logo` to the `info` "object" in the OpenAPI schema: {* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *} - ### Cache the OpenAPI schema You can use the property `.openapi_schema` as a "cache", to store your generated schema. @@ -70,19 +65,14 @@ That way, your application won't have to generate the schema every time a user o It will be generated only once, and then the same cached schema will be used for the next requests. - {* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *} - ### Override the method Now you can replace the `.openapi()` method with your new function. - - {* ../../docs_src/extending_openapi/tutorial001.py hl[29] *} - ### Check it Once you go to http://127.0.0.1:8000/redoc you will see that you are using your custom logo (in this example, **FastAPI**'s logo): diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index 5d8f879d1..a6219e481 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -35,10 +35,8 @@ Depending on your use case, you might prefer to use a different library, but if Here's a small preview of how you could integrate Strawberry with FastAPI: - {* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} - You can learn more about Strawberry in the Strawberry documentation. And also the docs about Strawberry with FastAPI. From 04194dc191c0818b1f75e7fe89d9206f96e112a1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 22:39:58 +0000 Subject: [PATCH 57/83] =?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 2e5ff95dc..8816c511f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio). ### Translations From 95ebac1a89a8f729ef78a72dfd44d4335faf7c86 Mon Sep 17 00:00:00 2001 From: Philip Okiokio <55271518+philipokiokio@users.noreply.github.com> Date: Sun, 27 Oct 2024 23:53:46 +0100 Subject: [PATCH 58/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/how-to/custom-docs-ui-assets.md`=20(#12557)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/custom-docs-ui-assets.md | 24 +++++--------------- 1 file changed, 6 insertions(+), 18 deletions(-) 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 16c873d11..abcccb499 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,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 hl[8] *} ### Include the custom docs @@ -36,9 +34,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 hl[2:6,11:19,22:24,27:33] *} /// tip @@ -54,9 +50,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 hl[36:38] *} ### Test it @@ -158,9 +152,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 hl[9] *} ### Include the custom docs for static files @@ -176,9 +168,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 hl[2:6,14:22,25:27,30:36] *} /// tip @@ -194,9 +184,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 hl[39:41] *} ### Test Static Files UI From dbc3008f5a3418271c31e7e3fe1051a7649f7289 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 22:54:10 +0000 Subject: [PATCH 59/83] =?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 8816c511f..40fe191a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio). * 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio). From 96a6d469e917076749b36603f509a8adc39a050c Mon Sep 17 00:00:00 2001 From: Tony Ly <15992943+tonyjly@users.noreply.github.com> Date: Sun, 27 Oct 2024 16:31:16 -0700 Subject: [PATCH 60/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/encoder.md`=20(#12597)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/encoder.md | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md index 039ac6714..e2eceafcc 100644 --- a/docs/en/docs/tutorial/encoder.md +++ b/docs/en/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ You can use `jsonable_encoder` for that. It receives an object, like a Pydantic model, and returns a JSON compatible version: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`. From adf89d1d9fdc8ea03bc0f3361b3d5e4b6835cf6c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 27 Oct 2024 23:31:38 +0000 Subject: [PATCH 61/83] =?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 40fe191a7..c687c7e0f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio). * 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio). From 269a22454443c6d977f702fb41d3d40cff149123 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Mon, 28 Oct 2024 11:29:51 +0100 Subject: [PATCH 62/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/tutorial/background-tasks.md`=20(#12600)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/background-tasks.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index d971d293d..e14d5a8e8 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -16,9 +16,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 hl[1,13] *} **FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. @@ -32,18 +30,14 @@ 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 hl[6:9] *} ## Ajouter une tâche d'arrière-plan Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` : -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` reçoit comme arguments : @@ -57,9 +51,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 hl[13,15,22,25] *} Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. From 0279f6dd5fc5613308d4dabd5af477a3ac8d42e9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:30:19 +0000 Subject: [PATCH 63/83] =?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 c687c7e0f..d2e40bf39 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio). * 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev). From 218d3c352429674d18dad0a42747dcbcbb9fb36a Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Mon, 28 Oct 2024 11:32:37 +0100 Subject: [PATCH 64/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/fr/docs/tutorial/path-params-numeric-validations.md`=20(#1?= =?UTF-8?q?2601)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-params-numeric-validations.md | 274 +----------------- 1 file changed, 10 insertions(+), 264 deletions(-) diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md index 82e317ff7..b3635fb86 100644 --- a/docs/fr/docs/tutorial/path-params-numeric-validations.md +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ 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` : -//// tab | Python 3.10+ - -```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 - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -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_an_py310.py hl[1,3] *} /// info @@ -74,57 +24,7 @@ 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 : -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// 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.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!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} /// note @@ -154,37 +54,11 @@ 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 : -//// tab | Python 3.8 non-Annotated - -/// tip - -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 hl[7] *} 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()`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// 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_py39.py hl[10] *} ## Ordonnez les paramètres comme vous le souhaitez (astuces) @@ -209,29 +83,13 @@ 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 hl[7] *} # Avec `Annotated` 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 `*`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// 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_py39.py hl[10] *} ## Validations numériques : supérieur ou égal @@ -239,35 +97,7 @@ 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`. -//// 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!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -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_an_py39.py hl[10] *} ## Validations numériques : supérieur ou égal et inférieur ou égal @@ -276,35 +106,7 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -//// 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!} -``` - -//// - -//// tab | 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!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Validations numériques : supérieur et inférieur ou égal @@ -313,35 +115,7 @@ La même chose s'applique pour : * `gt` : `g`reater `t`han * `le` : `l`ess than or `e`qual -//// 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!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -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_an_py39.py hl[10] *} ## Validations numériques : flottants, supérieur et inférieur @@ -353,35 +127,7 @@ Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. 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!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.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!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Pour résumer From 96c5566a5b31422965e0e1b383ef0128b0acde7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antony=20Ar=C3=A9valo?= Date: Mon, 28 Oct 2024 05:33:43 -0500 Subject: [PATCH 65/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/es/docs/tutorial/cookie-params.md`=20(#12602)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/tutorial/cookie-params.md | 104 +------------------------ 1 file changed, 2 insertions(+), 102 deletions(-) diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index e858e34e8..db3fc092e 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Puedes definir parámetros de Cookie de la misma manera que defines parámetros Primero importa `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_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 | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Consejo - -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_an_py310.py hl[3]*} ## Declarar parámetros de `Cookie` @@ -64,57 +14,7 @@ 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: -//// 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 | Consejo - -Es preferible utilizar la versión `Annotated` si es posible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Consejo - -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_an_py310.py hl[9]*} /// note | "Detalles Técnicos" From fe3922311f255a7ae0092c21e5c916b8d5ad0081 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:34:51 +0000 Subject: [PATCH 66/83] =?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 d2e40bf39..e381ba3b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio). From 76126c45e7d03c87bf0f4ad928d5861e229e8b91 Mon Sep 17 00:00:00 2001 From: Mohamed Salman Date: Mon, 28 Oct 2024 16:05:06 +0530 Subject: [PATCH 67/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/dataclasses.md`=20(#12603)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/dataclasses.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index efc07eab2..2936c6d5d 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -4,9 +4,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 hl[1,7:12,19:20] *} This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. @@ -34,9 +32,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 hl[1,7:13,19] *} The dataclass will be automatically converted to a Pydantic dataclass. @@ -52,9 +48,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 hl[1,5,8:11,14:17,23:25,28] *} 1. We still import `field` from standard `dataclasses`. From bcd55f8c099128a5c00783e418f9d8f96c3db1d3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:35:33 +0000 Subject: [PATCH 68/83] =?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 e381ba3b7..8a44e27f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93). * 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly). From 2bd2ccbd1930d58fafe5acb1f2990f5c25b6653a Mon Sep 17 00:00:00 2001 From: Mohamed Salman Date: Mon, 28 Oct 2024 16:06:22 +0530 Subject: [PATCH 69/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/events.md`=20(#12604)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/events.md | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index efce492f4..19465d891 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -30,9 +30,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 hl[16,19] *} 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*. @@ -50,9 +48,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 hl[14:19] *} The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -64,9 +60,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 hl[1,13] *} 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: @@ -88,9 +82,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 hl[22] *} ## Alternative Events (deprecated) @@ -112,9 +104,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 hl[8] *} In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -126,9 +116,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 hl[6] *} Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. From 3ea198f23c68eacd5b9d537b8114eb381b3dd426 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:37:16 +0000 Subject: [PATCH 70/83] =?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 8a44e27f6..0c11a9dd7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93). * 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane). From 8a4652d8b4ba1b558fbbee7db1e0e1bec4e64594 Mon Sep 17 00:00:00 2001 From: Mohamed Salman Date: Mon, 28 Oct 2024 16:08:23 +0530 Subject: [PATCH 71/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/advanced/openapi-webhooks.md`=20(#12605)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/openapi-webhooks.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index eaaa48a37..97aaa41af 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -32,9 +32,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 hl[9:13,36:53] *} The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. From 794d4b3a9b7b391f6b7bbcf6044fed7af31475fe Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:39:28 +0000 Subject: [PATCH 72/83] =?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 0c11a9dd7..3fc4b6baf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93). * 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane). From 86d8e729c8f39c6ae6816ffc1d54533bd0f73799 Mon Sep 17 00:00:00 2001 From: Rabin Lama Dong Date: Mon, 28 Oct 2024 14:42:34 +0400 Subject: [PATCH 73/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for=20?= =?UTF-8?q?`docs/en/docs/how-to/custom-docs-ui-assets.md`=20(#12623)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/custom-docs-ui-assets.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 abcccb499..f717c98fa 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -118,9 +118,7 @@ After that, your file structure could look like: * Import `StaticFiles`. * "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 hl[7,11] *} ### Test the static files From 70869200bdbb5952d296356f18848ec5eb301cce Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:42:48 +0000 Subject: [PATCH 74/83] =?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 3fc4b6baf..f8bad8450 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93). From f6a6366e42fa5b0c00991582e8f64a3c50100aa9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 10:50:28 +0000 Subject: [PATCH 75/83] =?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 f8bad8450..1d8910635 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong). * 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec). From 26702a65253d60980828bcbf648e1363d3684195 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Mon, 28 Oct 2024 12:13:18 +0100 Subject: [PATCH 76/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/response-status-code.md`=20(#12620)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/response-status-code.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 73af62aed..a32faa40b 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ The same way you can specify a response model, you can also declare the HTTP sta * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note @@ -76,9 +74,7 @@ To know more about each status code and which code is for what, check the Date: Mon, 28 Oct 2024 11:13:38 +0000 Subject: [PATCH 77/83] =?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 1d8910635..1107ec7bf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/response-status-code.md`. PR [#12620](https://github.com/fastapi/fastapi/pull/12620) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong). * 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec). * 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec). From cb2c56008d0792b9e1f0d21ea19c8c8d7ebb0e05 Mon Sep 17 00:00:00 2001 From: Abdul Hadi Bharara <32545366+bharara@users.noreply.github.com> Date: Mon, 28 Oct 2024 16:18:17 +0500 Subject: [PATCH 78/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in=20`?= =?UTF-8?q?docs/en/docs/tutorial/dependencies/index.md`=20(#12615)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/dependencies/index.md | 180 +------------------- 1 file changed, 4 insertions(+), 176 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index b50edb98e..596ce1599 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ 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: -//// tab | Python 3.10+ - -```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 hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.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!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} That's it. @@ -113,113 +63,13 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi ### Import `Depends` -//// 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!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### 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: -//// tab | Python 3.10+ - -```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 hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ 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!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently. @@ -276,29 +126,7 @@ 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: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```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!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip From 38bb9f934ba23e6545452fbfe74821f4a0446319 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 11:19:26 +0000 Subject: [PATCH 79/83] =?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 1107ec7bf..c49904533 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes in `docs/en/docs/tutorial/dependencies/index.md`. PR [#12615](https://github.com/fastapi/fastapi/pull/12615) by [@bharara](https://github.com/bharara). * 📝 Update includes in `docs/en/docs/tutorial/response-status-code.md`. PR [#12620](https://github.com/fastapi/fastapi/pull/12620) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong). * 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec). From ec9976f7a6bb27b11e68ce2e44fb64acaaed5bbb Mon Sep 17 00:00:00 2001 From: Rabin Lama Dong Date: Mon, 28 Oct 2024 15:21:54 +0400 Subject: [PATCH 80/83] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for=20?= =?UTF-8?q?`docs/en/docs/how-to/conditional-openapi.md`=20(#12624)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/conditional-openapi.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index 6cd0385a2..bd6cad9a8 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -29,9 +29,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 hl[6,11] *} Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. From f2b633ebeeb261fc6809a76925211ba4a14943ea Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 11:24:36 +0000 Subject: [PATCH 81/83] =?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 c49904533..c0c0721d5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes for `docs/en/docs/how-to/conditional-openapi.md`. PR [#12624](https://github.com/fastapi/fastapi/pull/12624) by [@rabinlamadong](https://github.com/rabinlamadong). * 📝 Update includes in `docs/en/docs/tutorial/dependencies/index.md`. PR [#12615](https://github.com/fastapi/fastapi/pull/12615) by [@bharara](https://github.com/bharara). * 📝 Update includes in `docs/en/docs/tutorial/response-status-code.md`. PR [#12620](https://github.com/fastapi/fastapi/pull/12620) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong). From 5c3326941970d181598704ae3d7c48a4873ab2cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=86=8C=EC=97=B0?= <54532519+dhdld@users.noreply.github.com> Date: Mon, 28 Oct 2024 20:29:32 +0900 Subject: [PATCH 82/83] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translation?= =?UTF-8?q?=20for=20`docs/ko/docs/fastapi-cli.md`=20(#12515)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/fastapi-cli.md | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/ko/docs/fastapi-cli.md diff --git a/docs/ko/docs/fastapi-cli.md b/docs/ko/docs/fastapi-cli.md new file mode 100644 index 000000000..3a976af36 --- /dev/null +++ b/docs/ko/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI**는 FastAPI 애플리케이션을 실행하고, 프로젝트를 관리하는 등 다양한 작업을 수행할 수 있는 커맨드 라인 프로그램입니다. + +FastAPI를 설치할 때 (예: `pip install "fastapi[standard]"` 명령어를 사용할 경우), `fastapi-cli`라는 패키지가 포함됩니다. 이 패키지는 터미널에서 사용할 수 있는 `fastapi` 명령어를 제공합니다. + +개발용으로 FastAPI 애플리케이션을 실행하려면 다음과 같이 `fastapi dev` 명령어를 사용할 수 있습니다: + +
+ +```console +$ fastapi dev 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 - 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 [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다. + +FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다. + +프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀 + +내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인
Uvicorn을 사용합니다. 😎 + +## `fastapi dev` + +`fastapi dev` 명령을 실행하면 개발 모드가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 활성화되어, 코드에 변경이 생기면 서버를 자동으로 다시 시작합니다. 하지만 이 기능은 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 따라서 개발 환경에서만 사용하는 것이 좋습니다. 또한, 서버는 컴퓨터가 자체적으로 통신할 수 있는 IP 주소(`localhost`)인 `127.0.0.1`에서 연결을 대기합니다. + +## `fastapi run` + +`fastapi run` 명령을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 비활성화되어 있습니다. 또한, 사용 가능한 모든 IP 주소인 `0.0.0.0`에서 연결을 대기하므로 해당 컴퓨터와 통신할 수 있는 모든 사람이 공개적으로 액세스할 수 있습니다. 이는 일반적으로 컨테이너와 같은 프로덕션 환경에서 실행하는 방법입니다. + +애플리케이션을 배포하는 방식에 따라 다르지만, 대부분 "종료 프록시(termination proxy)"를 활용해 HTTPS를 처리하는 것이 좋습니다. 배포 서비스 제공자가 이 작업을 대신 처리해줄 수도 있고, 직접 설정해야 할 수도 있습니다. + +/// tip + +자세한 내용은 [deployment documentation](deployment/index.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +/// From 8669a92dac5ec065f144705bf682226362277c1c Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 11:31:18 +0000 Subject: [PATCH 83/83] =?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 c0c0721d5..84ffb2e8d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/fastapi-cli.md`. PR [#12515](https://github.com/fastapi/fastapi/pull/12515) by [@dhdld](https://github.com/dhdld). * 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-change-status-code.md`. PR [#12547](https://github.com/fastapi/fastapi/pull/12547) by [@9zimin9](https://github.com/9zimin9). ## 0.115.4