Browse Source

Merge branch 'master' into fix-duplicate-special-dependency-handling

pull/12406/head
Peter Volf 7 months ago
committed by GitHub
parent
commit
e9e58dd28f
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 2
      .pre-commit-config.yaml
  2. 12
      docs/en/docs/advanced/dataclasses.md
  3. 24
      docs/en/docs/advanced/events.md
  4. 4
      docs/en/docs/advanced/openapi-webhooks.md
  5. 4
      docs/en/docs/how-to/conditional-openapi.md
  6. 4
      docs/en/docs/how-to/custom-docs-ui-assets.md
  7. 15
      docs/en/docs/release-notes.md
  8. 180
      docs/en/docs/tutorial/dependencies/index.md
  9. 12
      docs/en/docs/tutorial/response-status-code.md
  10. 104
      docs/es/docs/tutorial/cookie-params.md
  11. 16
      docs/fr/docs/tutorial/background-tasks.md
  12. 274
      docs/fr/docs/tutorial/path-params-numeric-validations.md
  13. 83
      docs/ko/docs/fastapi-cli.md

2
.pre-commit-config.yaml

@ -14,7 +14,7 @@ repos:
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace - id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.0 rev: v0.7.1
hooks: hooks:
- id: ruff - id: ruff
args: args:

12
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 <a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a> the same way: But FastAPI also supports using <a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a> the same way:
```Python hl_lines="1 7-12 19-20" {* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *}
{!../../docs_src/dataclasses/tutorial001.py!}
```
This is still supported thanks to **Pydantic**, as it has <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>. This is still supported thanks to **Pydantic**, as it has <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>.
@ -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: You can also use `dataclasses` in the `response_model` parameter:
```Python hl_lines="1 7-13 19" {* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *}
{!../../docs_src/dataclasses/tutorial002.py!}
```
The dataclass will be automatically converted to a Pydantic dataclass. 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: 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 hl[1,5,8:11,14:17,23:25,28] *}
{!../../docs_src/dataclasses/tutorial003.py!}
```
1. We still import `field` from standard `dataclasses`. 1. We still import `field` from standard `dataclasses`.

24
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: We create an async function `lifespan()` with `yield` like this:
```Python hl_lines="16 19" {* ../../docs_src/events/tutorial003.py hl[16,19] *}
{!../../docs_src/events/tutorial003.py!}
```
Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. 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`. 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 hl[14:19] *}
{!../../docs_src/events/tutorial003.py!}
```
The first part of the function, before the `yield`, will be executed **before** the application starts. 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**". That converts the function into something called an "**async context manager**".
```Python hl_lines="1 13" {* ../../docs_src/events/tutorial003.py hl[1,13] *}
{!../../docs_src/events/tutorial003.py!}
```
A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: 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. 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 hl[22] *}
{!../../docs_src/events/tutorial003.py!}
```
## Alternative Events (deprecated) ## 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"`: 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 hl[8] *}
{!../../docs_src/events/tutorial001.py!}
```
In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. 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"`: 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 hl[6] *}
{!../../docs_src/events/tutorial002.py!}
```
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.

4
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()`. 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 hl[9:13,36:53] *}
{!../../docs_src/openapi_webhooks/tutorial001.py!}
```
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.

4
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: For example:
```Python hl_lines="6 11" {* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *}
{!../../docs_src/conditional_openapi/tutorial001.py!}
```
Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`.

4
docs/en/docs/how-to/custom-docs-ui-assets.md

@ -118,9 +118,7 @@ After that, your file structure could look like:
* Import `StaticFiles`. * Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path. * "Mount" a `StaticFiles()` instance in a specific path.
```Python hl_lines="7 11" {* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *}
{!../../docs_src/custom_docs_ui/tutorial002.py!}
```
### Test the static files ### Test the static files

15
docs/en/docs/release-notes.md

@ -9,6 +9,16 @@ hide:
### Docs ### 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).
* 📝 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).
* 📝 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/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). * 📝 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). * 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev).
@ -16,8 +26,13 @@ hide:
### Translations ### 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). * 🌐 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).
### Internal
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12707](https://github.com/fastapi/fastapi/pull/12707) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
## 0.115.4 ## 0.115.4
### Refactors ### Refactors

180
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: It is just a function that can take all the same parameters that a *path operation function* can take:
//// tab | Python 3.10+ {* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
```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!}
```
////
That's it. That's it.
@ -113,113 +63,13 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi
### Import `Depends` ### Import `Depends`
//// tab | Python 3.10+ {* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
```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!}
```
////
### Declare the dependency, in the "dependant" ### 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: The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:
//// tab | Python 3.10+ {* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
```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!}
```
////
Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently. 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: 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+ {* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
```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!}
```
////
/// tip /// tip

12
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()` * `@app.delete()`
* etc. * etc.
```Python hl_lines="6" {* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
{!../../docs_src/response_status_code/tutorial001.py!}
```
/// note /// note
@ -76,9 +74,7 @@ To know more about each status code and which code is for what, check the <a hre
Let's see the previous example again: Let's see the previous example again:
```Python hl_lines="6" {* ../../docs_src/response_status_code/tutorial001.py hl[6] *}
{!../../docs_src/response_status_code/tutorial001.py!}
```
`201` is the status code for "Created". `201` is the status code for "Created".
@ -86,9 +82,7 @@ But you don't have to memorize what each of these codes mean.
You can use the convenience variables from `fastapi.status`. You can use the convenience variables from `fastapi.status`.
```Python hl_lines="1 6" {* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *}
{!../../docs_src/response_status_code/tutorial002.py!}
```
They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them: They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:

104
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`: Primero importa `Cookie`:
//// tab | Python 3.10+ {* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3]*}
```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!}
```
////
## Declarar parámetros de `Cookie` ## 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: 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+ {* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9]*}
```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!}
```
////
/// note | "Detalles Técnicos" /// note | "Detalles Técnicos"

16
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é. 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 hl[1,13] *}
{!../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. **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. 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 hl[6:9] *}
{!../../docs_src/background_tasks/tutorial001.py!}
```
## Ajouter une tâche d'arrière-plan ## 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()` : 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 hl[14] *}
{!../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` reçoit comme arguments : `.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 : **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 hl[13,15,22,25] *}
{!../../docs_src/background_tasks/tutorial002.py!}
```
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.

274
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` : Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` :
//// tab | Python 3.10+ {* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
```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!}
```
////
/// info /// 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 : 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+ {* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[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!}
```
////
/// note /// 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 : Ainsi, vous pouvez déclarer votre fonction comme suit :
//// tab | Python 3.8 non-Annotated {* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *}
/// tip
Préférez utiliser la version `Annotated` si possible.
///
```Python hl_lines="7"
{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
////
Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. 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+ {* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *}
```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!}
```
////
## Ordonnez les paramètres comme vous le souhaitez (astuces) ## 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 <abbr title="De : K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Même s'ils n'ont pas de valeur par défaut. 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 <abbr title="De : K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Même s'ils n'ont pas de valeur par défaut.
```Python hl_lines="7" {* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *}
{!../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
# Avec `Annotated` # 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 `*`. 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+ {* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *}
```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!}
```
////
## Validations numériques : supérieur ou égal ## 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`. Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`.
//// tab | Python 3.9+ {* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
```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!}
```
////
## Validations numériques : supérieur ou égal et inférieur ou égal ## 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 * `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual * `le` : `l`ess than or `e`qual
//// tab | Python 3.9+ {* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *}
```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!}
```
////
## Validations numériques : supérieur et inférieur ou égal ## 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 * `gt` : `g`reater `t`han
* `le` : `l`ess than or `e`qual * `le` : `l`ess than or `e`qual
//// tab | Python 3.9+ {* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *}
```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!}
```
////
## Validations numériques : flottants, supérieur et inférieur ## 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 <abbr title="less than"><code>lt</code></abbr>. Et la même chose pour <abbr title="less than"><code>lt</code></abbr>.
//// tab | Python 3.9+ {* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *}
```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!}
```
////
## Pour résumer ## Pour résumer

83
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` 명령어를 사용할 수 있습니다:
<div class="termy">
```console
$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u>
<font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font>
<font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font>
<font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files
<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮
│ │
│ 🐍 main.py │
│ │
╰──────────────────────╯
<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font>
<font color="#3465A4">INFO </font> Found importable FastAPI app
╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮
│ │
<span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span>
│ │
╰──────────────────────────╯
<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font>
<span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436"></font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"></font></span>
<span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span>
<span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span>
<font color="#4E9A06">INFO</font>: Will watch for changes in these directories: [&apos;/home/user/code/awesomeapp&apos;]
<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)
<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font>
<font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]
<font color="#4E9A06">INFO</font>: Waiting for application startup.
<font color="#4E9A06">INFO</font>: Application startup complete.
```
</div>
`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다.
FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다.
프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀
내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인 <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a>을 사용합니다. 😎
## `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}에서 확인할 수 있습니다.
///
Loading…
Cancel
Save